Autolayout 下面的 Layer.cornerRadius
一、问题:
如何在Autolayout模式中设置一个UIView的layer.cornerRadius?
二、解决:
UiView的layer目前还不支持Autolayout设置约束,因此如果想设置一个layer.cornerRadius的大小,必须传递的是一个值。
如果被设置的UIView尺寸会发生变化,也就是动态的大小,那么就需要在约束发生变化的时候,主动更新layer.cornerRadius对应的大小
那么具体分两种情况来对待:
第一种,UIView的尺寸不变化的时候:
1)在Xcode中设置layer.cornerRadius
2)使用代码
注意代码的位置,需要在View初始化的时候,比如ViewDidload,initView的时候
@interface ViewController () @property (weak, nonatomic) IBOutlet UIImageView *imgView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor yellowColor]; self.imgView.backgroundColor = [UIColor blueColor]; self.imgView.layer.cornerRadius = self.view.bounds.size.height/2; self.imgView.layer.masksToBounds = YES; } @end
但是需要注意一种情况,如果这个View的尺寸未计算得到的时候,需要放在 viewDidLayoutSubviews (VC),和viewDidLayout中(View)
第二种,UIView的尺寸变化的时候:
这种时候因为UIView的尺寸发生变化,那么需要在尺寸信息生成之后,进行调整。
如果是VC,那么在viewDidLayoutSubviews或者ViewDidAppear的回调中。
如果是UIView,苹果建议将约束代码放在updateConstraints回调中,这样可以提升性能。
//重写updateViewConstraints方法,进行约束的更新 - (void)updateViewConstraints { [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) { make.center.mas_equalTo(self.view); // 初始宽、高为100,优先级最低 make.width.height.mas_equalTo(100 * self.scacle).priorityLow(); // 最大放大到整个view make.width.height.lessThanOrEqualTo(self.view); }]; [super updateViewConstraints]; } // 通知需要更新约束,但是不立即执行 [self setNeedsUpdateConstraints]; // 立即更新约束,以执行动态变换 // update constraints now so we can animate the change [self updateConstraintsIfNeeded]; // 执行动画效果, 设置动画时间 [UIView animateWithDuration:0.2 animations:^{ [self layoutIfNeeded]; }];