問(wèn)題描述
我有一個(gè)帶有一些控制器和一些視圖的 UIViewController
.其中兩個(gè)視圖(網(wǎng)格單元)是其他 nib.我有從網(wǎng)格單元到文件所有者的出口,但它們不會(huì)自動(dòng)加載.
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
.這將啟動(dòng)一個(gè)無(wú)限循環(huán).
So I try to override GridCell.m
's initWithCoder
.
This starts an infinite loop.
我知道可以重寫(xiě) initWithFrame
并從代碼中添加子視圖,但這不是我想要的.我希望能夠在 Interface Builder 中移動(dòng)視圖并讓 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.
我該如何實(shí)現(xiàn)這一目標(biāo)?
How do I go about achieving this?
編輯 1
我正試圖在 Alexander 的幫助下讓它工作.這就是我現(xiàn)在設(shè)置它的方式:MainView 具有 UIView,其自定義類設(shè)置為 GridCell.它在 MainView/File's Owner 中有一個(gè)出口.
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 中刪除所有初始化代碼并為我的自定義類設(shè)置一個(gè)出口
Removed all init-code from GridCell.m and set up an outlet to my custom class
雖然 MainView 仍然不顯示 GridCell.沒(méi)有錯(cuò)誤,只是一個(gè)孤獨(dú)的、空白的地方,紅色開(kāi)關(guān)應(yīng)該在的地方.我做錯(cuò)了什么?
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?
我非常接近以編程方式執(zhí)行此操作.不過(guò),我很想學(xué)習(xí)如何用筆尖做到這一點(diǎn).
I'm very close to just doing this programmatically. I would love to learn how to this with nibs though.
推薦答案
加載 nib 會(huì)導(dǎo)致 initWithCoder 再次被調(diào)用,所以你只想在子類當(dāng)前沒(méi)有任何子視圖的情況下這樣做.
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;
}
這篇關(guān)于覆蓋 initWithCoder 時(shí)的無(wú)限循環(huán)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!