objective-c - 如何避免总是创建 UINavigationControllers?

标签 objective-c ios uinavigationcontroller presentmodalviewcontroller

在我的应用程序中,我有很多模态视图需要在导航 Controller 中呈现,所以我最终做了很多这样的事情:

MyModalController *modal = [[MyModalController alloc] init];
UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:modal];
[modal release];

[self presentModalViewController:navCon];
[navCon release];

理想情况下,我想简化这一点,以便 MyModalController 负责创建导航 Controller 。这种事情的任何最佳实践?我想我总是可以添加一个像 +navigationControllerWithModalController 这样的方法,但我想听听其他人是如何做到的。

另外,我希望能够将委托(delegate)附加到 MyModalController,这样我就可以将信息发送回当前的 View Controller ,这样我就知道何时关闭它。

最佳答案

那么每个 View 都需要在一个独特的导航 Controller 中呈现吗?然后你可能会稍微改变你的计划并写下类似的内容:

@interface UINavigationController (NavigationControllerWithViewController)

+ navigationControllerWithRootViewControllerOfType:(Class)type;

@end

/* ... */


@implementation UINavigationController (NavigationControllerWithViewController)

+ navigationControllerWithRootViewControllerOfType:(Class)type
{
     UIViewController *modal = [[type alloc] init];
     UINavigationController *navCon = [[UINavigationController alloc] 
                                               initWithRootViewController:modal];
     [modal release];

     return [navCon autorelease];
}

@end

所以你在 UINavigationController 上声明了一个类别(也就是说,一种向类添加新方法而无需对其进行子类化或访问原始源的方法),它执行实例化 View Controller 、创建相关导航 Controller 并返回它的常见工作。然后你可以这样做:
UINavigationController *controller =
        [UINavigationController navigationControllerWithRootViewControllerOfType:
                    [MyModalController class]];

[self presentModalViewController:controller];

或者传入任何类型的 View Controller 来代替 MyModalController .如果您通过的类(class)不是 UIViewController那么你最终会将不是 View Controller 的东西传递给 UINavigationController -initWithRootViewController:方法,所以要小心。

至于委托(delegate),我猜你会做一个协议(protocol)和委托(delegate)的通常声明,然后在你的导航 Controller 类别方法中添加一个额外的参数来提供一个委托(delegate)。您将失去有用和无用的编译时警告,但您可能想要这样做:
[(id)modal setDelegate:delegate];

如果您尝试使用没有委托(delegate)属性的东西来实例化导航 Controller ,这将导致异常。

关于objective-c - 如何避免总是创建 UINavigationControllers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7274752/

相关文章:

objective-c - View 和其他对象的泄漏

iOS - NavigationBar Title 与之前的 viewController 重叠

ios - 在插入第二个 VC 时出现错误堆栈未更新

ios - 来自 UIImage 的 NSData。以错误的方向上传到服务器

objective-c - sizeWithFont :constrainedToSize:lineBreakMode: and contentSize (text height in Objective-C) 之间的确定关系

iOS:如何在我的应用程序中实现 Accordion (下拉)UI,如图所示?

ios - Viewcontroller 呈现问题

ios - Swift:带有 Selector 参数的函数返回一个非托管的 <AnyObject>?

ios - 带有嵌入式导航 Controller 的 Popover 不考虑后退导航的大小

ios - 如何在 objective-c 中返回对象的 UIColor?