How to properly use modal view controller with the xcode 4.2 storyboard

无人久伴 提交于 2019-12-10 13:17:44

问题


I was wondering how to properly use the storyboard to put up a view controller modally. Personally I prefer working with xibs, but it seems that the storyboard is gaining popularity and will be the way to go in the future.

The way I would normally put up a view controller modally would be like this: let's say we have ViewControllerA (A for short) and ViewControllerB (B for short). I would then normally put a protocol in B.h specifying the delegate method when B wants to be dismissed and add the id<theProtocol> delegate field as an assign property. Assuming i'm busy in A and I want to present B modally, I would write:

B* b = [[B alloc] initWithNibName:@"B" bundle:nil];
b.delegate = self;
[self presentModalViewController:B animated:YES];

Using the storyboard, I know it's possible to put up a different view controller in a modal way by ctrl-dragging from a button to a viewcontroller and selecting modal as transition type. I'm just wondering though; where do I set the delegate of the new view controller? What's the correct practice of passing things to your modal view controller? I don't really know what the whole deal with Segues is...


回答1:


Take a look at this tutorial

According to it, you should set the delegate as follows:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"AddPlayer"])
    {
        UINavigationController *navigationController = 
          segue.destinationViewController;
        PlayerDetailsViewController 
          *playerDetailsViewController = 
            [[navigationController viewControllers] 
              objectAtIndex:0];
        playerDetailsViewController.delegate = self;
    }
}

Where @"AddPlayer" is the name of your 'modal' segue




回答2:


Instead of using the navigation controller you could directly use the UIStoryboardSegue object passed in prepareForSegue. It has a property called destinationViewController which is the view controller that is being instantiated. I find that a lot cleaner. This is an example.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"AddPlayer"])
    {
        PlayerDetailsViewController 
          *playerDetailsViewController = 
            (PlayerDetailsViewController *) segue.destinationViewController;

        playerDetailsViewController.delegate = self;
    }
}

IMO I think that storyboards are great because they function like a blueprint of your application. Also I've never liked nibs. =D



来源:https://stackoverflow.com/questions/8261360/how-to-properly-use-modal-view-controller-with-the-xcode-4-2-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!