gpt4 book ai didi

swift - 试图创建一个圆圈 UIImageView 导致它消失

转载 作者:行者123 更新时间:2023-11-28 11:28:41 25 4
gpt4 key购买 nike

我有一个简单的 UIImageView,试图将它的 cornerRadius 设置为其宽度的一半,从而导致图像消失。这是我的:

    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
}()

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

最佳答案

问题是在设置 cornerRadius 时没有获得正确的 ImageView 框架。

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

这段代码对我有用

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])
}

}

关于swift - 试图创建一个圆圈 UIImageView 导致它消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57401365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com