自动布局和圆角半径(砌体) - Autolayout (with Masonry) with corner radius

- 此内容更新于:2016-02-17
主题:

  我想布置一个圆形UIImageView砌筑。所以我创建了UIImageView:然后我创建ImageView[自我的约束。imageViewmas_makeConstraints:^(MASConstraintMaker*使){
  make.centerX.equalTo(self.mas_centerX);
  make.top.equalTo(self.mas_top);。抵消([[UIViewub_padding]floatValue]);
  make.bottom.equalTo(self.descriptionLabel.mas_top);。抵消(-[[UIViewub_padding]floatValue]);
  make.height.equalTo(self.descriptionLabel.mas_height).priorityHigh();
  make.width.equalTo(self.imageView.mas_height);
  });
  然后我尝试应用这些约束,然后设置圆角半径。但仍未凝结的框架(但它讲到后来,当我把它模拟器)。布局时调用什么方法做了什么?

原文:

I would like to layout a circular UIImageView with Masonry. So I have created the UIImageView like this:

[self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerX.equalTo(self.mas_centerX);
    make.top.equalTo(self.mas_top).with.offset([[UIView ub_padding] floatValue]);
    make.bottom.equalTo(self.descriptionLabel.mas_top).with.offset(-[[UIView ub_padding] floatValue]);
    make.height.equalTo(self.descriptionLabel.mas_height).priorityHigh();
    make.width.equalTo(self.imageView.mas_height);
}];

I then created the constraints for the ImageView

[self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerX.equalTo(self.mas_centerX);
    make.top.equalTo(self.mas_top).with.offset([[UIView ub_padding] floatValue]);
    make.bottom.equalTo(self.descriptionLabel.mas_top).with.offset(-[[UIView ub_padding] floatValue]);
    make.height.equalTo(self.descriptionLabel.mas_height).priorityHigh();
    make.width.equalTo(self.imageView.mas_height);
}];

I then tried to have these constraints applied and then set the corner radius.

    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
    [self layoutIfNeeded];
    self.imageView.layer.cornerRadius = self.imageView.frame.size.width/2;

But the frame of self.imageView is still unset (but it does get layed out later when I view it on the simulator). What method is called when the layout is done?

网友:你寻找的方法吗?它叫做每次一个视图控制器的布局。

(原文:Are you looking for the -(void)viewDidLayoutSubviews method? It's called every time a view controller does layout.)

网友:我不知道砌筑。这就是为什么我不把它写成一个答案。显然你可以访问UIImageView对象及其层。说你准备好了吗?

(原文:I don't know Masonry. That is why I don't write this as an answer. Apparently you have access to the UIImageView object and its layer. Dis you set self.imageView.layer.maskksToBounds=YES; ?)

楼主:我注意到,但我希望UIView本身也会有这样的一个方法…

(原文:I noticed that, but I was hoping that the UIView itself would have a method like that...)

解决方案:
设置你的圆角半径后调用在你的视图的方法:这样可以确保布局发生之前应用角半径的50%(就我而言高度/宽度创建一个圆),并计算正确。
原文:

Setup your corner radius after calling super... in your view's layoutSubviews method:

-(void)layoutSubviews{
    [super layoutSubviews];
    [self applyCornerRadii];
}

This ensures layout has occurred before attempting to apply corner radii (which in my case is 50% of the height/width to create a circle), and it is calculated correctly.