iOS xib的使用详解
1.File’s Owner为nil
UIView *demo1 = [[[NSBundle mainBundle] loadNibNamed:@"demo1" owner:nil options:nil] lastObject];
CGRect rect = demo1.frame;
rect.origin.y = 100;
demo1.frame = rect;
[self.view addSubview:demo1];
2.File’s Owner有值, File’s Owner可以是任何实例,不一定是控制器
// 下面是demo2_class1.h, xib和demo2_class1连线产生的
@property (weak, nonatomic) IBOutlet UIView *purpleView;
@property (weak, nonatomic) IBOutlet UIView *blueView;
// 下面是mainViewController.m
demo2_class1 *demo2 = [[demo2_class1 alloc]init];
NSLog(@"load前:demo2.purpleView.frame-------%@",NSStringFromCGRect(demo2.purpleView.frame));
NSLog(@"load前:demo2.blueView.frame-------%@",NSStringFromCGRect(demo2.blueView.frame));
// 此时self.view是没值的,也就是说往self.view上加东西,是不会有效果的
// [self.view addSubview:demo2.purpleView];
[[[NSBundle mainBundle] loadNibNamed:@"demo2" owner:demo2 options:nil] lastObject];
NSLog(@"load后:demo2.purpleView.frame-------%@",NSStringFromCGRect(demo2.purpleView.frame));
NSLog(@"load后:demo2.blueView.frame-------%@",NSStringFromCGRect(demo2.blueView.frame));
[self.view addSubview:demo2.purpleView];
说明:xib只有loadNib完之后,File’s Owner的IBOutlet才会自动初始化
3. 如果在<2>的代码的基础上,新建一个dog类,把Owner改成dog,其他都不改
Dog *dog = [[Dog alloc]init];
[[[NSBundle mainBundle] loadNibNamed:@"demo2" owner:dog options:nil] lastObject];
运行程序,程序崩溃,崩溃原因如下,由此可见,在loadNibNamed时,会去找owner的IBOutlet,并对IBOutlet做setValue的操作
2015-02-03 14:49:17.285 xib开发[31342:60b] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Dog 0x8d4bc90> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key blueView.'
4.如果在<2>的代码的基础上,给demo2_classs1这个类添加实例方法 - (IBAction)clickMe;并且在xib上添加个按钮,按钮和clickMe做连线
在模拟器上点击那个按钮,有打印.
5.xib里的view指定为自定义的类. PS:File’s Owner不用去设
--------------------------------------------------分割线--------------------------------------------------
5.1 Demo3 class一般是自定义类,需要提供一个遍历构造方法,方便使用
+ (instancetype)initWithXib{
return [[[NSBundle mainBundle] loadNibNamed:@"demo3" owner:nil options:nil] lastObject];
}
5.2 补充:如果需要对xib里各个子控件做个性化的设置,可以在awakeFromNib做相应设置
- (void)awakeFromNib{
self.backgroundColor = [UIColor redColor];
}
5.3 在mainViewController.m里使用xib
demo3_class *demo3 = [demo3_class initWithXib];
CGRect rect = demo3.frame;
rect.origin.y = 200;
demo3.frame = rect;
[self.view addSubview:demo3];
6.xib的File’s Owner是UIViewController的子类,File’s Owner的view 就是xib的view
// 提供便捷方法
+ (instancetype)viewControllerFromXib{
return [[self alloc] initWithNibName:@"demo4" bundle:nil];
}
看看MainViewController怎么使用:
// 稳妥的做法
demo4_ViewController *demo4VC = [[demo4_ViewController alloc]initWithNibName:@"demo4" bundle:nil];
// 或者用便捷方法,如果xib文件的名字和类名称一样,可以用便捷方法
// demo4_ViewController *demo4VC = [demo4_ViewController demo4ViewController];
[self.view addSubview:demo4VC.view];
// 父子控制器
[self addChildViewController:demo4VC];