switch between uiviews with buttons and not uinavi

2019-02-05 14:15发布

I have seen the post for How to switch views by buttons on iPhone? but this doesn't answer how to switch back and forth between views with buttons. The person that asked the question settled on the answer that they could switch between views with uinavigationcontroller.

I put the following code in an ibaction that kicks off when a button is pressed in the primary view.

         PhoneNumberViewController *phoneNumberViewController1 = [[PhoneNumberViewController alloc] initWithNibName:@"PhoneNumberView2" bundle:nil];
self.phoneNumberViewController = phoneNumberViewController1;
[self.view removeFromSuperview];
[self.view insertSubview: phoneNumberViewController1.view atIndex:0];

When this code executes the whole view just goes blank. If I omit the removefromsuperview portion then the view disappears behind my button but the button still remains. I'm not sure if this is the right way to switch between buttons but if anyone knows how to do this please help. Also if anyone knows about any example projects that switch between views with buttons let me know.

Thanks a million!

2条回答
倾城 Initia
2楼-- · 2019-02-05 14:52

The technique I usually use involves creating a superview class which contains a toolbar at the bottom, and a content view UIView class filling the rest of the screen.

I then add subviews to the content view to change the views based on button clicks. This approach makes it so the toolbar on the same is constant across all views. I start by defining a helper function like this:

-(void) clearContentView {
    //helper to clear content view
    for (UIView *view in [self.contentView subviews]){
        [view removeFromSuperview];
    }
}

My IBAction then looks like this:

-(IBAction) buttonClicked{
    self.title = @"Images"; //change title of view
    [self clearContentView]; //clear content view
    [self.contentView addSubview:self.imagesViewController.view]; //add new view
    [self.imagesViewController viewWillAppear:YES]; //make sure new view is updated
    [self enableButtons];  //enable all other buttons on toolbar
    self.imagesButton.enabled = NO;  //disable currently selected button
}
查看更多
可以哭但决不认输i
3楼-- · 2019-02-05 15:08

You removed the view controller's view from it's superview and then added a subview to it. The view hierarchy is broken at the view controller's superview (likely your window). That is why you are getting a blank screen.

You'd likely want to keep a reference around to the original view and then swap it out to the new view by setting the view controller's view to the new view.

// origView is an instance variable/IBOutlet to your original view.
- (IBAction)switchToPhoneView:(id)sender {
  if (origView == nil)
    origView = self.view;
  self.view = phoneViewController.view;
}

- (IBAction)switchToOriginalView:(id)sender {
  self.view = origView;
}
查看更多
登录 后发表回答