在模态视图控制器之间切换

时间:2012-01-06 21:49:57

标签: ios

我的应用程序允许用户在两​​个不同的模态视图控制器之间切换(用于两种不同类型的数据输入)。以下代码用于工作(在iOS 4.3及更早版本中):

    UIViewController * parent = current.parentViewController;
    [current dismissModalViewControllerAnimated:NO];
    svc.modalPresentationStyle = UIModalPresentationFormSheet;
    [parent presentModalViewController:svc animated:NO];
    [svc release];

但不再(在iOS 5中) - “当前”视图控制器解散,但“svc”未显示。

知道它为什么破了(即我做错了什么)? 任何想法如何“正确”(这样它在5.0以及4.3及更早版本上工作)?

1 个答案:

答案 0 :(得分:3)

除了一件事,杰夫·海伊的评论是完全正确的。您应该在最初显示第一个模态视图控制器的视图控制器的-viewDidAppear:方法中执行此操作。

示例:

// MyViewController.h
@interface MyViewController : UIViewController {
    BOOL _shouldPresentSecondModalViewController;
}
@end

// MyViewController.m
@implementation MyViewController
- (void)viewDidAppear:(BOOL)animated {
    if(_shouldPresentSecondModalViewController) {
        UINavigationController *myNavCon;
        // Code to create second modal navigation controller
        [self presentModalViewController:myNavCon animated:YES];
        _shouldPresentSecondModalViewController = NO;
    }
}

- (void)presentFirstViewController {
    UINavigationController *myNavCon;
    // Code to create the first navigation controller
    _shouldPresentSecondModalViewController = YES;
    [self presentModalViewController:myNavCon animated:YES];
}
@end

修改
现在,如果要在两个模态视图控制器之间传递数据,可以使用委托。

// FirstModalViewControllerDelegate.h
@protocol FirstModalViewControllerDelegate
@optional
- (void)controller:(FirstModalViewControllerDelegate *)vc shouldShowData:(id)anyType;
@end

// MyViewController.h
@interface MyViewController : UIViewController <FirstModalViewControllerDelegate> {
    id _dataToDisplay;
}
@end

// MyViewController.m
@implementation MyViewController
- (void)viewDidAppear:(BOOL)animated {
    if(_dataToDisplay != nil) {
        UINavigationController *myNavCon;
        // Code to create second modal navigation controller
        [self presentModalViewController:myNavCon animated:YES];
        [_dataToDisplay release];
        _dataToDisplay = nil;
    }
}

- (void)presentFirstViewController {
    UINavigationController *myNavCon;
    FirstModalViewController *myCon;
    // Code to create the first modal view controller

    [myCon setDelegate:self];

    myNavCon = [[UINavigationController alloc] initWithRootViewController:myCon];

    [self presentModalViewController:myNavCon animated:YES];
    [myNavCon release];
}

- (void)controller:(FirstModalViewControllerDelegate *)vc shouldShowData:(id)anyType {
    /* This method will get called if the first modal view controller wants to display
    some data. If the first modal view controller doesn't call this method, the
    _dataToDisplay instance variable will stay nil. However, in that case, you'll of
    course need to implement other methods to, like a response to a Done button, dismiss
    the modal view controller */
    [self dismissModalViewController];
    _dataToDisplay = [anyType retain];
}
@end