在自定义 UINavigationController 中强制执行特定 rootViewController 的推荐方法是啥?

Posted

技术标签:

【中文标题】在自定义 UINavigationController 中强制执行特定 rootViewController 的推荐方法是啥?【英文标题】:What is the recommended way to enforce a specific rootViewController in a custom UINavigationController?在自定义 UINavigationController 中强制执行特定 rootViewController 的推荐方法是什么? 【发布时间】:2012-06-28 07:20:10 【问题描述】:

我正在构建一个可供其他 iPhone 开发人员使用的 iPhone SDK。

此 SDK 的主要用途是呈现一个 UI,使用户能够完成某个过程。

这个 UI 应该被封装在 UINavigationController 中,因为它是由构成流程的多个 UIViewController 组成的。

我希望将使用我的 SDK 的开发人员初始化我的自定义 UINavigationController,然后以他们想要的方式呈现它。

我想强制我的自定义导航控制器的 rootViewController 将是 SDK 中的特定 ViewController,开发人员将无法使用不同的 rootViewController 对其进行初始化。

实现这一目标的推荐方法是什么?

【问题讨论】:

【参考方案1】:

你不应该继承苹果文档中写的UINavigationController

这个类不用于子类化。相反,您使用实例 在您希望应用程序的用户的情况下保持原样 界面以反映内容的层次结构。

如果您是 ios 5,请使用 UIViewControllers 的新容器 API。

Implementing a Container View Controller

使用这种方法,您可以强制执行您的根控制器并将其隐藏给用户。

如果 iOS 5 不可用,请参阅我之前的回答 Handle different view controllers within an application: creating Custom Content View Controllers。

希望对您有所帮助。

【讨论】:

【参考方案2】:

您可以编写一个类方法来实例化您的视图控制器:

+(MyViewController*)myViewController 
    MyViewController* = myViewController = [[MyViewController* alloc] init];
    myViewController.rootViewController = [[MyDesiredRootViewController alloc] init];
    return myViewController;

开发人员将使用此方法来初始化您的视图控制器,并且所有初始化工作都对他们隐藏。

【讨论】:

我真的很喜欢这种方式,这就是我真正实施的方式【参考方案3】:

如果 rootViewController 是不同的类,你可能会初始化失败

- (id)initWithRootViewController:(UIViewController*)rootController

    if(![rootController isKindOfClass:[YourRootViewController class]])
        return nil;

    //Do default init stuff


【讨论】:

我宁愿不让它失败,而是强迫它成为我想要的。我不希望开发人员甚至知道“内部”视图控制器。 奥马尔,导航控制器不应该被子类化,因为可能会发生奇怪的事情.. 是的,你是 100% 正确的,他应该扩展 UIViewController 并使用 UIViewController 包含属性来实现他自己的导航控制器

以上是关于在自定义 UINavigationController 中强制执行特定 rootViewController 的推荐方法是啥?的主要内容,如果未能解决你的问题,请参考以下文章

织梦CMS如何在自定义表单页调用arclist标签啊,怎么在自定义表单页调用无效!

在自定义回调中访问验证数据

在自定义页面中创建自定义路由

在自定义操作中启用/禁用功能

何时在自定义 UIVIew 中添加 CAAnimation?

如何在自定义对话框上显示进度对话框?