我有一个带有一些控制器和一些视图的 UIViewController
.其中两个视图(网格单元)是其他 nib.我有从网格单元到文件所有者的出口,但它们不会自动加载.
I have a UIViewController
with some controllers and some views. Two of these views (Grid Cell) are other nibs. I've got outlets from the Grid Cells to File's Owner, but they aren't loaded automatically.
所以我尝试覆盖 GridCell.m
的 initWithCoder
.这将启动一个无限循环.
So I try to override GridCell.m
's initWithCoder
.
This starts an infinite loop.
我知道可以重写 initWithFrame
并从代码中添加子视图,但这不是我想要的.我希望能够在 Interface Builder 中移动视图并让 Xcode 使用正确的框架初始化视图.
I know it's possible to just override initWithFrame
and add the subview from code, but this is not what I want. I want to be able to move the view around in Interface Builder and have Xcode initialize the view with the right frame.
我该如何实现这一目标?
How do I go about achieving this?
编辑 1
我正试图在 Alexander 的帮助下让它工作.这就是我现在设置它的方式:MainView 具有 UIView,其自定义类设置为 GridCell.它在 MainView/File's Owner 中有一个出口.
I'm trying to get it working with the help of Alexander. This is how I've now got it set up: MainView has UIView with a Custom class set as GridCell. It got an outlet in the MainView/File's Owner.
从 GridCell.m 中删除所有初始化代码并为我的自定义类设置一个出口
Removed all init-code from GridCell.m and set up an outlet to my custom class
虽然 MainView 仍然不显示 GridCell.没有错误,只是一个孤独的、空白的地方,红色开关应该在的地方.我做错了什么?
The MainView don't still display the GridCell though. There's no error, just a lonely, empty space where the red switch should be. What am I doing wrong?
我非常接近以编程方式执行此操作.不过,我很想学习如何用笔尖做到这一点.
I'm very close to just doing this programmatically. I would love to learn how to this with nibs though.
加载 nib 会导致 initWithCoder 再次被调用,所以你只想在子类当前没有任何子视图的情况下这样做.
Loading the nib causes initWithCoder to be called again, so you only want to do so if the subclass currently doesn't have any subviews.
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
if (self.subviews.count == 0) {
UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
UIView *subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
subview.frame = self.bounds;
[self addSubview:subview];
}
}
return self;
}
这篇关于覆盖 initWithCoder 时的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!