Changing view controller when Segmented Control changes

前端 未结 4 1660
终归单人心
终归单人心 2020-12-02 16:17

This problem is driving me crazy. I\'m trying to change the viewController when the user changes the selected \"tab\" of the segmented control. I\'ve spent a co

4条回答
  •  一向
    一向 (楼主)
    2020-12-02 16:45

    UISegmentedControl is a little different in that it doesn't have a delegate protocol, you have to use the "add target" style. In your case what you want to do is add a target to be notified when the UISegmentedControl changes (which is likely the parent view controller), and then that target can deal with the tab switching.

    For example:

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

    In this example, the code is being invoked from some view/controller that has access to the variable for the segmented control. We add ourself to get the changedSegmentedControl: method invoked.

    Then you would have another method like so:

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

    Note: this is untested code written from memory -- please consult the docs accordingly.

提交回复
热议问题