12

这个问题快把我逼疯了。我正在尝试更改viewController用户更改分段控件的选定“选项卡”的时间。我花了几个小时进行研究,但无法找到有效的答案或通过情节提要完成的答案。

这真的让我很困扰,因为设置选项卡应用程序非常简单,但是尝试像选项卡应用程序一样使用分段控件是行不通的。我已经知道如何检测在分段控件中选择了哪个索引。我怎样才能做到这一点?

非常感谢你。

4

4 回答 4

42

注意:使用 iOS 5+ 的视图控制器包含代码更新了答案,包括 @interface 部分

在我的一个应用程序中,我在导航栏中有一个带有段控件的视图控制器,然后单击“选项卡”切换视图控制器。基本思想是拥有一个视图控制器数组,并使用段索引(和 indexDidChangeForSegmentedControl IBAction)在它们之间切换。

我的应用程序中的示例代码(iOS 5 或更高版本)(这是用于 2 个视图控制器,但它很容易扩展到多个视图控制器);该代码比 iOS 4 稍长,但会保持对象图完整。此外,它使用 ARC:

@interface MyViewController ()
// Segmented control to switch view controllers
@property (weak, nonatomic) IBOutlet UISegmentedControl *switchViewControllers;

// Array of view controllers to switch between
@property (nonatomic, copy) NSArray *allViewControllers;

// Currently selected view controller
@property (nonatomic, strong) UIViewController *currentViewController;
@end

@implementation UpdateScoreViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    // Create the score view controller
    ViewControllerA *vcA = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerA"];

    // Create the penalty view controller
    ViewControllerB *vcB = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerB"];

    // Add A and B view controllers to the array
    self.allViewControllers = [[NSArray alloc] initWithObjects:vcA, vcB, nil];

    // Ensure a view controller is loaded
    self.switchViewControllers.selectedSegmentIndex = 0;
    [self cycleFromViewController:self.currentViewController toViewController:[self.allViewControllers objectAtIndex:self.switchViewControllers.selectedSegmentIndex]];
}

#pragma mark - View controller switching and saving

- (void)cycleFromViewController:(UIViewController*)oldVC toViewController:(UIViewController*)newVC {

    // Do nothing if we are attempting to swap to the same view controller
    if (newVC == oldVC) return;

    // Check the newVC is non-nil otherwise expect a crash: NSInvalidArgumentException
    if (newVC) {

        // Set the new view controller frame (in this case to be the size of the available screen bounds)
        // Calulate any other frame animations here (e.g. for the oldVC)
        newVC.view.frame = CGRectMake(CGRectGetMinX(self.view.bounds), CGRectGetMinY(self.view.bounds), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));

        // Check the oldVC is non-nil otherwise expect a crash: NSInvalidArgumentException
        if (oldVC) {

            // Start both the view controller transitions
            [oldVC willMoveToParentViewController:nil];
            [self addChildViewController:newVC];

            // Swap the view controllers
            // No frame animations in this code but these would go in the animations block
            [self transitionFromViewController:oldVC
                              toViewController:newVC
                                      duration:0.25
                                       options:UIViewAnimationOptionLayoutSubviews
                                    animations:^{}
                                    completion:^(BOOL finished) {
                                        // Finish both the view controller transitions
                                        [oldVC removeFromParentViewController];
                                        [newVC didMoveToParentViewController:self];
                                        // Store a reference to the current controller
                                        self.currentViewController = newVC;
                                    }];

        } else {

            // Otherwise we are adding a view controller for the first time
            // Start the view controller transition
            [self addChildViewController:newVC];

            // Add the new view controller view to the ciew hierarchy
            [self.view addSubview:newVC.view];

            // End the view controller transition
            [newVC didMoveToParentViewController:self];

            // Store a reference to the current controller
            self.currentViewController = newVC;
        }
    }
}

- (IBAction)indexDidChangeForSegmentedControl:(UISegmentedControl *)sender {

    NSUInteger index = sender.selectedSegmentIndex;

    if (UISegmentedControlNoSegment != index) {
        UIViewController *incomingViewController = [self.allViewControllers objectAtIndex:index];
        [self cycleFromViewController:self.currentViewController toViewController:incomingViewController];
    }

}
@end

原始示例(iOS 4 或更早版本):

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    // Create the score view controller
    AddHandScoreViewController *score = [self.storyboard instantiateViewControllerWithIdentifier:@"AddHandScore"];

    // Create the penalty view controller
    AddHandPenaltyViewController *penalty = [self.storyboard instantiateViewControllerWithIdentifier:@"AddHandPenalty"];

    // Add Score and Penalty view controllers to the array
    self.allViewControllers = [[NSArray alloc] initWithObjects:score, penalty, nil];

    // Ensure the Score controller is loaded
    self.switchViewControllers.selectedSegmentIndex = 0;
    [self switchToController:[self.allViewControllers objectAtIndex:self.switchViewControllers.selectedSegmentIndex]];
}

#pragma mark - View controller switching and saving

- (void)switchToController:(UIViewController *)newVC
{
    if (newVC) {
        // Do nothing if we are in the same controller
        if (newVC == self.currentViewController) return;

        // Remove the current controller if we are loaded and shown
        if([self.currentViewController isViewLoaded]) [self.currentViewController.view removeFromSuperview];

        // Resize the new view controller
        newVC.view.frame = CGRectMake(CGRectGetMinX(self.view.bounds), CGRectGetMinY(self.view.bounds), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));

        // Add the new controller
        [self.view addSubview:newVC.view];

        // Store a reference to the current controller
        self.currentViewController = newVC;
    }
}

- (IBAction)indexDidChangeForSegmentedControl:(UISegmentedControl *)sender {

    NSUInteger index = sender.selectedSegmentIndex;

    if (UISegmentedControlNoSegment != index) {
        UIViewController *incomingViewController = [self.allViewControllers objectAtIndex:index];
        [self switchToController:incomingViewController];
    }

}
于 2012-07-10T22:39:04.303 回答
5

我想说在 a 中更改子视图要简单得多UIViewController,您可以在情节提要中设置子视图并将它们连接到IBOulets控制器中,您可以hidden根据单击的控件将视图的属性设置为 YES 或 NO。

现在,如果您使用@Robotic Cat 的方法,这也是一个很好的解决方案,您可以在应用程序的工作方式上更加模块化,考虑到您必须使用我提出的解决方案将所有逻辑放在一个控制器中。

于 2012-07-10T22:40:09.703 回答
0

UISegmentedControl 有点不同,它没有委托协议,您必须使用“添加目标”样式。在您的情况下,您想要做的是添加一个目标,以便在 UISegmentedControl 更改时得到通知(这可能是父视图控制器),然后该目标可以处理选项卡切换。

例如:

[self.mainSegmentedControl addTarget:self action:@selector(changedSegmentedControl:) forControlEvents:UIControlEventValueChanged];

在此示例中,代码是从可以访问分段控件变量的某个视图/控制器调用的。我们添加自己以调用 changedSegmentedControl: 方法。

然后您将有另一种方法,如下所示:

- (void)changedSegmentedControl:(id)sender
{
   UISegmentedControl *ctl = sender;
   NSLog(@"Changed value of segmented control to %d", ctl.selectedSegmentIndex);
   // Code to change View Controller goes here
}

注意:这是从内存中编写的未经测试的代码——请相应地查阅文档。

于 2012-07-10T22:34:35.633 回答
0

看看这个 pod:https ://github.com/xmartlabs/XLMailBoxContainer 。它在视图控制器之间制作 UI 动画。这些视图控制器可以扩展 UITableViewController 或任何其他视图控制器。

我希望这对你有帮助!

于 2014-03-11T22:21:04.367 回答