layer.cornerRadius无法与NSLayoutConstraints结合使用(Swift 3)

Ste*_*fan 5 xcode ios nslayoutconstraint swift

以下是我的纵断面图约束,该视图渲染效果很好,但是宽度始终返回零。因此,最终约束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)
Run Code Online (Sandbox Code Playgroud)

有什么建议么?

在此处输入图片说明

Vas*_*vev 5

profileImageView.frame.width为零,因为它的框架尚未计算。在您的profileImageView覆盖layoutSubviews方法中:

override func layoutSubviews() {
    super.layoutSubviews()
    layer.cornerRadius = bounds.width / 2.0
}
Run Code Online (Sandbox Code Playgroud)

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

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    profileImageView.layer.cornerRadius = profileImageView.bounds.width / 2.0
}
Run Code Online (Sandbox Code Playgroud)