layer.cornerRadius与NSLayoutConstraints(swift 3)不兼容

时间:2017-05-10 19:04:15

标签: ios swift xcode nslayoutconstraint

下面是我的个人资料视图约束,视图渲染效果很好,但宽度始终为零。因此,最终约束profileImageView.layer.cornerRadius =(profile.frame.width / 2)每次都返回零。

    profileImageView.translatesAutoresizingMaskIntoConstraints = false


    addConstraint(NSLayoutConstraint(item: profileImageView, attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 0.125, constant: 0))


    addConstraint(NSLayoutConstraint(item: profileImageView, attribute: .height, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 0.125, constant: 0))




    addConstraint(NSLayoutConstraint(item: profileImageView, attribute: .centerY, relatedBy: .equal, toItem: containerView, attribute: .centerY, multiplier: 1, constant: 0))

    addConstraint(NSLayoutConstraint(item: profileImageView, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 0.25, constant: 0))

    profileImageView.layer.cornerRadius = (profileImageView.frame.width / 2)

有什么建议吗?

enter image description here

2 个答案:

答案 0 :(得分:2)

profileImageView.frame.width为零,因为它的帧尚未计算。在profileImageView覆盖layoutSubviews方法内:

override func layoutSubviews() {
    super.layoutSubviews()
    layer.cornerRadius = bounds.width / 2.0
}

或者,如果您正在使用视图控制器,请覆盖viewDidLayoutSubviews方法:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    profileImageView.layer.cornerRadius = profileImageView.bounds.width / 2.0
}

答案 1 :(得分:0)

UIViewController尚未布局,并且没有规模。假设这是在viewDidLayoutSubviews子类中,您可以将角半径代码放在override func viewDidLayoutSubviews() { profileImageView.layer.cornerRadius = (profileImageView.frame.width / 2) } 内:

int hitCount, missCount, evictionCount;
int s, E, b;