开发者

Switch 2 views with switch controller

This is the main view and I'd like to toggle two separa开发者_C百科ted views; for ON state and for OFF state.

How the code would look like?

Switch 2 views with switch controller


Do the following

  - (void)viewDidLoad //of mainViewController {
        //do viewController1 alloc init     // Gray Color
        [self.view addSubview:viewController1.view];

        //do viewController2 alloc init     //Red Color
        [self.view addSubview:viewController2.view];

        [viewController2.view setHidden:YES];
    }

//assign this method to segmented controls' valueChanged event
    - (IBAction)segmentControlClicked:(id)sender {
        UISegmentedControl *segmentedControl = (UISegmentedControl *)sender; // if segmented control is not declared as an IBOutlet
        if (segmentedControl.selectedSegmentIndex == 0) {
            [viewController1.view setHidden:NO];
            [viewController2.view setHidden:YES];
        }
        else if (segmentedControl.selectedSegmentIndex == 1) {
            [viewController2.view setHidden:NO];
            [viewController1.view setHidden:YES];
        }
    }

Make sure that the 'y' origin viewController1 and viewController2 are below the Segmented Control so that the segmented control is not hidden.


you can take two view in xib and add both view in main view at view did load and set the property hidden for one which you don't want to show, and then set hidden property TRUE or FALSE for switch control event on off.


Try the following

- (IBAction)segmentControlClicked:(id)sender {
    if (!viewController1) {
        //do alloc init
    }
    if (!viewController2) {
        //do alloc init
    }

    UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
    if (segmentedControl.selectedSegmentIndex == 0) {
        [viewController1.view setHidden:NO];
        [viewController2.view setHidden:YES];
    }
    else if (segmentedControl.selectedSegmentIndex == 1) {
        [viewController2.view setHidden:NO];
        [viewController1.view setHidden:YES];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜