好的,StackOverflow上有几十篇关于这个问题的帖子,但没有一个是特别清楚的解决方案.我想创建一个带有随附的xib文件的自定义UIView
.要求是:
- 没有单独的
UIViewController
-一个完全独立的类 - 类中的插座,允许我设置/获取视图的属性
我目前的做法是:
-
覆盖
-(id)initWithFrame:
-(id)initWithFrame:(CGRect)frame { self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] objectAtIndex:0]; self.frame = frame; return self; }
-
在我的视图控制器中使用
-(id)initWithFrame:
以编程方式实例化MyCustomView *myCustomView = [[MyCustomView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)]; [self.view insertSubview:myCustomView atIndex:0];
这很好(尽管从不调用[super init]
,只是使用加载的nib的内容设置对象似乎有点可疑——这里有建议add a subview in this case也很好).然而,我也希望能够从故事板实例化视图.所以我可以:
- 在情节提要中的父视图上放置
UIView
- 将其自定义类设置为
MyCustomView
-
Override
-(id)initWithCoder:
–我见过的代码通常符合以下模式:-(id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self initializeSubviews]; } return self; } -(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self initializeSubviews]; } return self; } -(void)initializeSubviews { typeof(view) view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] objectAtIndex:0]; [self addSubview:view]; }
当然,这不起作用,因为无论我使用上述方法,还是以编程方式实例化,都会在输入-(void)initializeSubviews
并从文件加载nib时递归调用-(id)initWithCoder:
.
其他几个SO问题也涉及到这一点,例如here、here、here和here.然而,没有一个答案能令人满意地解决问题:
- 一种常见的建议似乎是将整个类嵌入到UIViewController中,然后在那里进行nib加载,但对我来说,这似乎不太理想,因为它只需要添加另一个文件作为包装器
有没有人能给出解决这个问题的建议,让工作插座在定制的UIView
中以最小的小题大做/没有薄的控制器包装?或者,有没有一种替代的、更干净的方式来用最少的样板代码来做事情?