我不确定这样做的最佳做法,所以我想我会问。
这是该计划的目标:
目前,我有它工作,但每个嵌套视图控制器不是视图控制器,而是子类UIView。我觉得这是不好的做法,因为我在视图控制器方式中使用这些UIViews,但没有视图控制器的功能(即viewDidLoad)。此外,这些UIViews正在采用UIViewController的常用委托方法(它真正引发了红色标志)。
这实际上是不好的做法吗?
当我尝试切换到UIViewControllers时我害怕的事情是,我仍然需要创建一个UIView的子类来识别当我通过以下方式加载nib时指向哪个视图:
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,因为bundle中还有其他UIView对象。但话说回来,这种情况可能会比现在的情况好一些。
另一种解决方案可能是使MainViewController成为所有需要委托的UIView的委托,并创建包含每个嵌套nib的委托方法的MainViewController类别。
这里有什么想法吗?
答案 0 :(得分:3)
为每个UIViewController
类型创建一个SubclassedUIView
子类,勾选为接口创建XIB文件的选项,并将所有代码移到该类,指向self.view
。然后使用.xib为该视图控制器打开Interface Builder,并根据需要配置UIView
的可视外观。要操作主视图控制器中的可视元素,您必须为每个元素分配“标记”编号或创建一大堆IBOutlet
实例变量,并将它们连接到IB中的元素。使用UINavigationController
正确显示视图控制器的方式是:
/* 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还允许您将导航控制器添加到主视图控制器.xib文件中,并提供后退按钮文本,主标题等。实现子类视图控制器时,覆盖initWithNibName:bundle:
并设置{ {1}}以及您想要的self.navigationItem.title
的任何其他属性。
编辑:你的意思是你必须能够在其他视图中操纵某些子视图的特定属性吗?如同,你需要一直访问所有这些?如果是这种情况,则在加载主视图控制器时建立与子类视图的连接,即:
self.navigationItem
然后在您的子类控制器中,您可以通过以下几种方式访问主控制器:
- (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];
self.parentViewController
或类似内容的调用(基本上,您的应用程序代表对应用程序主视图的引用)。[(MyCustomAppDelegateClass *)[[NSApplication sharedApplication] delegate] rootView]
属性和ivar。您可以在使用@property (assign)
。有用的文档:
答案 1 :(得分:0)
显然,根据How to add an UIViewController's view as subview,我正在做的事情很好。