简体   繁体   中英

Reusing view inside navigation controller and as a modal popup with storyboards

I have a detail view that allows you to edit/create an item. From one screen I want to be able to create these items, so I use a modal window with Cancel/Save in the toolbar.

In the second window I am coming from a tableview so I want to display the item in the existing navigation controller.

I am wondering if I can use the same view/view controller in the storyboard to complete both tasks? Do I need to add the toolbar manually to the view and hide it if I detect I am launching from a nav controller?

My other solution would be to add an empty nav controller and have the modal popup button point to the nav controller which in turn contains the edit view (Then add the buttons when I find that it is the only view in the navigation stack.)

Should I do one of those things? Or should I just duplicate the view in my storyboard?

You can do this with a single view controller. I would recommend that you 'push' the edit/create view controller. This will cover the case where you just want to view the information and give you the ability to navigate back easily. In the case where you want to edit the information you would create your cancel and save toolbar buttons and programmatically as follows in viewWillAppear of the cancel/save view controller. When you set them they will simply overlay the current button provided by the push (no need to hide anything):

 UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                   target:self
                                     action:@selector(cancelButton)];
    self.navigationItem.leftBarButtonItem = cancelButton;

UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
                                 initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                 target:self
                               action:@selector(saveButton)];
self.navigationItem.rightBarButtonItem = saveButton;

In your prepareForSegue method in the parent viewController, you could set a property that would instruct the cancel/save viewController to either show or edit as follows:

if ([segue.identifier isEqualToString:@"toCancelAddVC"]) {
    UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
    destinationVC = (CancelAddViewController*)navController.topViewController;
destinationVC.myState = @"cancelSave"; // or @"view"

Note: You can also use this myState property to control the behavior you want (ie set all fields to readonly, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM