尝试创建一个圆 UIImageView 导致它消失



我有一个简单的UIImageView,试图将其角半径设置为宽度的一半,导致图像消失。 这是我所拥有的:

private let profileImg: UIImageView = {
let img = UIImageView(image: UIImage(named: "profileplaceholder"))
img.translatesAutoresizingMaskIntoConstraints = false
img.heightAnchor.constraint(equalToConstant: 100).isActive = true
img.widthAnchor.constraint(equalToConstant: 100).isActive = true
img.layer.borderWidth = 1.0
img.layer.borderColor = UIColor.appPurple.cgColor
img.layer.cornerRadius = (img.frame.width / 2)
img.clipsToBounds = true
img.layer.masksToBounds = true
img.contentMode = .scaleAspectFill
return img
}()

我只是不明白这里有什么问题,以及为什么图像根本不会显示。

问题是在设置角半径时,它没有获得正确的图像视图框架。

添加/更改约束后,您可以使用layoutIfNeeded()它将强制布局视图。

这段代码对我有用

class ViewController: UIViewController {
var profileImageView : UIImageView = {
let img = UIImageView(image: UIImage(named: "0266554465"))
img.translatesAutoresizingMaskIntoConstraints = false
img.heightAnchor.constraint(equalToConstant: 300).isActive = true
img.widthAnchor.constraint(equalToConstant: 300).isActive = true
img.layoutIfNeeded()
img.layer.borderWidth = 1.0
img.layer.cornerRadius = (img.frame.width / 2)
img.clipsToBounds = true
return img
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.profileImageView)
let centerXConstraint = NSLayoutConstraint(item: profileImageView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: profileImageView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0)
view.addConstraints([centerXConstraint, centerYConstraint])
}
}

发生这种情况是因为您正在使用约束设置图像视图的大小,然后在应用约束之前使用框架计算拐角半径。如果您尝试打印出 img.frame.width 返回的内容,您应该会看到它不像您期望的那样是"50"。

快速解决方法是将角半径硬编码为所需的大小,但我建议您改为将图像视图创建与逻辑的其余部分分开。理想情况下,将 imageView/stackView 放在 xib 中,并在 viewDidLoad(( 中设置拐角半径。这将确保约束在您需要检索视图框架之前生效。

另一个建议 - 每次使用 profileImg 时,您的代码将按原样重新创建图像视图,这是低效的,可能会导致意外行为(即编辑配置文件图像可能不起作用(。将profileImg更改为IBOutlet将为您解决此问题,或者您可以在init((中设置其值以确保它只初始化一次。

最新更新