xib文件的使用分為兩種:
1伞梯,使用代碼載入
2,在其他xib文件中通過綁定class使用自定義的xib文件
而這兩種方法的實(shí)現(xiàn),對建立xib文件時的設(shè)置又各不相同爪膊,在子控件進(jìn)行了連線的情況下,因此 同一個xib文件不能同時使用兩種方法去調(diào)用這個xib文件
配置方式
1砸王,使用代碼載入
2E528362-A4F2-4AB9-8B8D-91B6AE871418.png
如上圖所示推盛,將 custom view 綁定class,連接內(nèi)部的子控件到接口提供使用
使用 自定義的xib時谦铃,如果沒有設(shè)置尺寸耘成,會更具在 xib 文件中的大小顯示
2,在其他xib文件中通過綁定class使用自定義的xib文件
BA088021-6F59-4346-B664-F627E9FB680E.png
如上圖所示驹闰,將 file’s owner 的 custom class 改為 CustomView瘪菌,在對子控件進(jìn)行連線
要在 xib 中使用自定義的 xib 控件,上面的配置只是基礎(chǔ)嘹朗,還需要實(shí)現(xiàn)下面的方法(介紹在參考文章中):
#import "CustomView.h"
@implementation CustomView
/**
* 這個方法需要設(shè)置 file's owner 綁定 class 時才使用
*/
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
UIView *containerView = [[[UINib nibWithNibName:@"CustomView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0];
CGRect newFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
containerView.frame = newFrame;
[self addSubview:containerView];
}
return self;
}
/* 或?qū)崿F(xiàn)這個方法 */
//- (id) awakeAfterUsingCoder:(NSCoder*)aDecoder {
// BOOL isJustAPlaceholder = ([[self subviews] count] == 0);
// if (isJustAPlaceholder) {
// CustomView* theRealThing = [[self class] getClassObjectFromNib];
//
// theRealThing.frame = self.frame; // ... (pass through selected properties)
//
// // Update 2013-07-23: make compatible with Auto Layout
// self.translatesAutoresizingMaskIntoConstraints = NO;
// theRealThing.translatesAutoresizingMaskIntoConstraints = NO;
//
// // convince ARC that we're legit -- Update 2013-03-10: unnecessary since at least Xcode 4.5
// CFRelease((__bridge const void*)self);
// CFRetain((__bridge const void*)theRealThing);
//
// return theRealThing;
// }
// return self;
//}
@end
可能出現(xiàn)的問題:
5ABA6A1B-229C-4807-B753-5808A966003C.png
這個問題的出現(xiàn)情景是:
使用代碼的方式使用 xib 文件
原因:
使用了第 2 種方式(在其他xib文件中通過綁定class使用自定義的xib文件)配置 xib 文件师妙,并且子控件進(jìn)行了連線;如果子控件沒有進(jìn)行連線骡显,是可以正常運(yùn)行的疆栏,不會報錯
解決自然是從新配置成第 1 中方式
參考文章:
http://www.tuicool.com/articles/ENv6Nf/
上面截圖直接使用文章提供的 demo
文章 demo 地址:https://github.com/wtlucky/nestedXibLoad