我不确定这样做的最佳做法,所以我想我会问。
这是该计划的目标:
目前,我让它工作,但是每个嵌套 View Controller 不是 View Controller ,而是一个子类 UIView。我觉得这是不好的做法,因为我以 View Controller 的方式使用这些 UIView,但没有 View Controller 的功能(即 viewDidLoad)。此外,这些 UIView 采用了 UIViewController 的常用委托(delegate)方法(这确实引发了危险信号)。
这实际上是不好的做法吗?
我在尝试切换到 UIViewControllers 时害怕的事情是,我仍然需要创建 UIView 的子类来识别当我通过以下方式加载 nib 时要指向哪个 View :
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
for (id object in bundle) {
if ([object isKindOfClass:[SubclassedUIView class]])
currentScreenViewController = (SubclassedUIView *)object;
}
我还没有检查,但我认为我必须在该语句中执行“SubclassedUIView”,而不仅仅是 UIView,因为捆绑包中还有其他 UIView 对象。但话又说回来,这种情况可能比目前的情况要好。
一个不同的解决方案可能是让 MainViewController 成为所有需要委托(delegate)的 UIView 的委托(delegate),并创建 MainViewController 的类别,其中包含每个嵌套 nib 的委托(delegate)方法。
这里有什么想法吗?
最佳答案
创建 UIViewController
每个 SubclassedUIView
的子类键入,勾选为接口(interface)创建 XIB 文件的选项,然后将所有代码移至该文件,将其指向 self.view
.然后使用该 View Controller 的 .xib 打开 Interface Builder 并配置 UIView
的视觉外观随你喜欢。要从主视图 Controller 操作可视元素,您必须为每个元素分配“标签”编号或创建一大堆 IBOutlet
实例变量并将它们连接到 IB 中的元素。使用 UINavigationController
正确呈现 View Controller 的方式是:
/* at the top of your main view controller */
#import "SubclassedUIViewController.h"
/* when navigating to the next view */
SubclassedUIViewController *newController = [[SubclassedUIViewController alloc] initWithNibName:@"SubclassedUIViewController" bundle:nil];
[(UILabel *)[newController.view viewWithTag:6] setText:@"Text"]; // example of accessing elements using tags
[newController.textLabel setText:@"Text 2"]; // example of accessing elements using IBOutlet connections
[self.navigationController pushViewController:newController animated:YES];
[newController release];
Interface Builder 还允许您将导航 Controller 添加到主视图 Controller .xib 文件并提供后退按钮文本、主标题等。当您实现子类 View Controller 时,覆盖
initWithNibName:bundle:
并设置self.navigationItem.title
和 self.navigationItem
的任何其他属性你要。编辑 : 你的意思是你必须能够在其他子类 View 中操作某些子类 View 的特定属性吗?例如,您需要始终访问所有这些?如果是这种情况,则在加载主视图 Controller 时连接到您的子类 View ,即:
- (void)viewDidLoad
{
[super viewDidLoad];
self.subclassedController1 = [[SubclassedUIViewController1 alloc] initWithNibName:@"SubclassedUIViewController1" bundle:nil];
// self.subclassedController2 = ... etc
}
/* in your loading next view code you can skip the alloc/init line */
[self.navigationController presentViewController:subclassedController2 animated:YES];
然后在您的子类 Controller 中,您可以通过以下几种方式访问主 Controller :
self.parentViewController
[(MyCustomAppDelegateClass *)[[NSApplication sharedApplication] delegate] rootView]
或类似的(基本上,您的应用程序委托(delegate)对应用程序主视图的引用)。 @property (assign)
属性和 ivar 指向指向主视图 Controller 的子类 Controller 。您可以在加载主视图 Controller 时使用 subclassedController1.mainViewController = self
分配它. 有用的文档:
关于objective-c - 带有嵌套 View Controller 的 iOS 自定义导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5426504/