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

有什么建议么?

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

最佳答案

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

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

或者,如果您使用的是 View Controller ,请重写viewDidLayoutSubviews方法:
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    profileImageView.layer.cornerRadius = profileImageView.bounds.width / 2.0
}

10-08 09:29