在使用xib加载子控件时,有时在布局上会产生一些问题,这时就要想到xib的autoresizingMask属性.
示例一
1.在控制器中用代码创建一个redView,给这个redView添加一个子view:blueView,并且这个blueView是从xib中加载的.
2.添加touchesBegin方法改变redView的大小.
- (void)viewDidLoad {
[super viewDidLoad];
//代码创建一个redView
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
redView.frame = CGRectMake(20, 20, 300, 300);
[self.view addSubview:redView];
self.redView = redView;
//从xib中加载一个blueView
UIView *blueView = [[[NSBundle mainBundle] loadNibNamed:@"BlueView" owner:nil options:nil]firstObject];
NSLog(@"%zd",blueView.autoresizingMask);
//将blueView添加到redView的子控件中
[redView addSubview:blueView];
}
//添加touchesBegin方法控制redView的大小
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
CGRect frame = self.redView.frame;
frame.size.width -= 50;
frame.size.height += 50;
self.redView.frame = frame;
}
如图可见blueView会随着redView大小改变而改变.这是应为xib的autoresizingMask问题,我们可以打印出这个值.
NSLog(@"%zd",blueView.autoresizingMask);
2016-04-17 15:10:59.052 自动拉伸宽高[6363:247788] 18
点开autoresizingMask属性
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
看,这几个枚举值和打印刚好说明blueView的autoresizingMask刚好是(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)这两个属性刚好是保证与superView左边右边,顶部和底部的距离不变.
如果我们不想让xib跟随父控件变化,只需要添加一句代码就可以啦~
blueView.autoresizingMask = UIViewAutoresizingNone;