xib加载时的autoresizingMask问题(一)

在使用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;
}
图1.gif

如图可见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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容