kle*_*vre 5 iphone inheritance objective-c uiviewcontroller nib
我正在尝试做一些非常棘手的事情,而且我仍然陷入困境.我正在尝试UIViewController使用从其他Nib文件继承的Nib文件来实例化UIViewController.
问题是我实例化我的儿子UIViewController.
// SonViewController
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
{
if ((self = [super initWithNibName:nibNameOrNil
bundle:nibBundleOrNil])) {
// Custom initialization.
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
init方法initWithNibName:bundle:应该调用super class它,但它只调用自己的nib文件.在超类中,我试图覆盖该initWithNibName:bundle:方法并将nibName自己放入:
// MotherViewController
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
{
if ((self = [super initWithNibName:@"MotherViewController"
bundle:nibBundleOrNil])) {
// Custom initialization.
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
它只是初始化并显示Mother Class它的IB对象.我理解为什么,但我开始认为不可能做我想做的事.有什么建议吗?
编辑:
我会像我那样使用我的SonViewController:
SonViewController *son = [[SonViewController alloc]
initWithNibName:@"SonViewController" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:son animated:YES];
[son release];
Run Code Online (Sandbox Code Playgroud)
它应该显示儿子和母亲IB对象......
问候,
kl94
我知道这是一个旧线程,但我刚刚在这里找到了一篇令人难以置信的博客文章。
本质上,您必须迭代父类的所有视图,并将它们作为子视图添加到子类中。以下是我在项目中的实现方式:
// ChildViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
[self addSubviewsFromSuperclass];
}
// ParentViewController.h
- (void)addSubviewsFromSuperclass;
// ParentViewController.m
- (void)addSubviewsFromSuperclass
{
UIView *selfView = self.view;
UIView *nibView = nil;
@try
{
nibView = [NSBundle.mainBundle loadNibNamed:NSStringFromClass([self superclass]) owner:self options:nil][0];
}
@catch (NSException *exception)
{
NSLog(@"Something exceptional happened while loading nib:\n%@", exception);
}
self.view = selfView;
for (UIView *view in nibView.subviews)
{
[self.view addSubview:view];
}
}
Run Code Online (Sandbox Code Playgroud)
addSuviewsFromSuperclass方法不是我的编码。我必须完全感谢我上面提到的博文的作者。下载他的示例项目,您将在他的 JMViewController.m 中找到它。