UI 세그먼트 컨트롤을 사용하여 보기를 전환하는 방법은 무엇입니까?
Apple이 'Top Payed'와 'Top Free'를 전환할 때 App Store에서 수행하는 방식과 유사하게 UIS Segmented Control의 여러 상태를 사용하여 보기를 전환하는 방법을 알아보려고 합니다.
가장 간단한 방법은 가시성을 전환하여 선택한 보기를 나타내는 두 개의 보기를 갖는 것입니다.다음은 보기를 처리하는 최적화된 방법이 아니라 UI 세그먼트 컨트롤을 사용하여 표시되는 보기를 전환하는 방법을 보여주는 방법에 대한 몇 가지 샘플 코드입니다.
- (IBAction)segmentSwitch:(id)sender {
UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
if (selectedSegment == 0) {
//toggle the correct view to be visible
[firstView setHidden:NO];
[secondView setHidden:YES];
}
else{
//toggle the correct view to be visible
[firstView setHidden:YES];
[secondView setHidden:NO];
}
}
물론 올바른 보기를 숨기거나 표시하기 위해 코드를 추가로 재요인화할 수 있습니다.
제 경우에는 보기가 상당히 복잡하며 메모리를 너무 많이 차지하기 때문에 다른 보기의 숨겨진 속성을 변경할 수 없습니다.
몇 가지 솔루션을 시도해 보았지만 그 중 어떤 솔루션도 제대로 작동하지 않거나 비정상적으로 수행했습니다. 특히 보기를 푸시/팝업할 때 navBar의 View(보기)에 세그먼트화된 Control이 항상 표시되지는 않습니다.
저는 적절한 방법으로 그것을 하는 방법을 설명하는 이슈에 대한 이 블로그 게시물을 발견했습니다.그는 WWDC'2010에서 애플 엔지니어들의 도움을 받아 이 솔루션을 고안한 것으로 보입니다.
http://redartisan.com/2010/6/27/uisegmented-control-view-switching-revisited
이 링크의 해결책은 지금까지 이 문제에 대해 찾은 최고의 해결책입니다.약간의 조정으로 하단의 탭바에서도 잘 작동했습니다.
또는 테이블인 경우 테이블과 cellForRowAt를 다시 로드할 수 있습니다.인덱스, 선택한 세그먼트 옵션을 기준으로 다른 데이터 소스의 테이블을 채웁니다.
한 가지 방법은 분할된 컨트롤이 있는 뷰에 여러 하위 뷰로 채우는 컨테이너 뷰를 설정하는 것입니다(세그먼트가 전환될 때 컨테이너 뷰의 유일한 하위 뷰로 추가).필요한 경우 "viewWillAppear" 및 "viewWillDispare"와 같은 중요한 방법을 전달해야 하지만, 이러한 하위 뷰에 대해 별도의 뷰 컨트롤러를 사용할 수도 있습니다.
일반적으로 IB에서 컨테이너로 메인 뷰를 배치할 수 있고 하위 뷰는 컨테이너가 허용하는 모든 공간을 채울 수 있기 때문에 매우 잘 작동합니다(자동 크기 마스크가 올바르게 설정되었는지 확인).
다음과 같은 설정으로 원하는 것을 정확히 수행하는 오픈 소스 구성 요소인 를 사용해 보십시오.UITabBarController
.
빠른 버전:
상위 보기 컨트롤러는 각 하위 보기 컨트롤러의 보기 크기와 위치를 설정하는 역할을 합니다.하위 뷰 컨트롤러의 뷰는 상위 뷰 컨트롤러의 뷰 계층 구조의 일부가 됩니다.
게으른 속성 정의:
private lazy var summaryViewController: SummaryViewController = {
// Load Storyboard
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
// Instantiate View Controller
var viewController = storyboard.instantiateViewController(withIdentifier: "SummaryViewController") as! SummaryViewController
// Add View Controller as Child View Controller
self.add(asChildViewController: viewController)
return viewController
}()
private lazy var sessionsViewController: SessionsViewController = {
// Load Storyboard
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
// Instantiate View Controller
var viewController = storyboard.instantiateViewController(withIdentifier: "SessionsViewController") as! SessionsViewController
// Add View Controller as Child View Controller
self.add(asChildViewController: viewController)
return viewController
}()
하위 보기 컨트롤러 표시/숨기기:
private func add(asChildViewController viewController: UIViewController) {
// Add Child View Controller
addChildViewController(viewController)
// Add Child View as Subview
view.addSubview(viewController.view)
// Configure Child View
viewController.view.frame = view.bounds
viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Notify Child View Controller
viewController.didMove(toParentViewController: self)
}
private func remove(asChildViewController viewController: UIViewController) {
// Notify Child View Controller
viewController.willMove(toParentViewController: nil)
// Remove Child View From Superview
viewController.view.removeFromSuperview()
// Notify Child View Controller
viewController.removeFromParentViewController()
}
세그먼트 컨트롤 탭 이벤트 관리
private func updateView() {
if segmentedControl.selectedSegmentIndex == 0 {
remove(asChildViewController: sessionsViewController)
add(asChildViewController: summaryViewController)
} else {
remove(asChildViewController: summaryViewController)
add(asChildViewController: sessionsViewController)
}
}
물론 하위 보기 컨트롤러 클래스 내에서 다음을 사용할 수 있습니다.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("Summary View Controller Will Appear")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("Summary View Controller Will Disappear")
}
참조: https://cocoacasts.com/managing-view-controllers-with-container-view-controllers/
@Ronnie Liew의 답변을 바탕으로, 저는 다음과 같은 것을 만들었습니다.
//
// ViewController.m
// ResearchSegmentedView
//
// Created by Ta Quoc Viet on 5/1/14.
// Copyright (c) 2014 Ta Quoc Viet. All rights reserved.
//
#define SIZE_OF_SEGMENT 56
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize theSegmentControl;
UIView *firstView;
UIView *secondView;
CGRect leftRect;
CGRect centerRect;
CGRect rightRect;
- (void)viewDidLoad
{
[super viewDidLoad];
leftRect = CGRectMake(-self.view.frame.size.width, SIZE_OF_SEGMENT, self.view.frame.size.width, self.view.frame.size.height-SIZE_OF_SEGMENT);
centerRect = CGRectMake(0, SIZE_OF_SEGMENT, self.view.frame.size.width, self.view.frame.size.height-SIZE_OF_SEGMENT);
rightRect = CGRectMake(self.view.frame.size.width, SIZE_OF_SEGMENT, self.view.frame.size.width, self.view.frame.size.height-SIZE_OF_SEGMENT);
firstView = [[UIView alloc] initWithFrame:centerRect];
[firstView setBackgroundColor:[UIColor orangeColor]];
secondView = [[UIView alloc] initWithFrame:rightRect];
[secondView setBackgroundColor:[UIColor greenColor]];
[self.view addSubview:firstView];
[self.view addSubview:secondView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)segmentSwitch:(UISegmentedControl*)sender {
NSInteger selectedSegment = sender.selectedSegmentIndex;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
if (selectedSegment == 0) {
//toggle the correct view to be visible
firstView.frame = centerRect;
secondView.frame = rightRect;
}
else{
//toggle the correct view to be visible
firstView.frame = leftRect;
secondView.frame = centerRect;
}
[UIView commitAnimations];
}
@end
.H 할당
UISegmentedControl *lblSegChange;
- (IBAction)segValChange:(UISegmentedControl *) sender
.M 선언
- (IBAction)segValChange:(UISegmentedControl *) sender
{
if(sender.selectedSegmentIndex==0)
{
viewcontroller1 *View=[[viewcontroller alloc]init];
[self.navigationController pushViewController:view animated:YES];
}
else
{
viewcontroller2 *View2=[[viewcontroller2 alloc]init];
[self.navigationController pushViewController:view2 animated:YES];
}
}
빠른 빠른 버전:
@IBAction func segmentControlValueChanged(_ sender: UISegmentedControl) {
if segmentControl.selectedSegmentIndex == 0 {
// do something
} else {
// do something else
}
}
언급URL : https://stackoverflow.com/questions/1047114/how-do-i-use-a-uisegmentedcontrol-to-switch-views
'sourcecode' 카테고리의 다른 글
jQuery 요소 내에서 마우스 위치 가져오기 (0) | 2023.08.01 |
---|---|
indexPath별로 적합한 ViewCell을 얻으려면 어떻게 해야 합니까? (0) | 2023.08.01 |
Angular2 재료 대화상자 자체 닫기 (0) | 2023.08.01 |
이름을 가진 커서가 이미 존재하는 이유는 무엇입니까? (0) | 2023.08.01 |
PL/SQL에서 날짜 범위에 걸쳐 반복하는 방법 (0) | 2023.07.27 |