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

标签 swift

我有一个简单的 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/

相关文章:

ios - SwiftUI - 如何从单独的类触发警报

ios - 无法在容器 View 中加载 xml 数据

ios - UICollectionView设置默认位置

ios - 从另一个 View Controller 更改选项卡栏选定项

swift - 显示具有编程约束的按钮

Swift 解包可选类变量产生失败

iOS Swift - 有没有办法将 subview 添加到表格单元格中并正确定位它?

ios - 从教程制作简单的 HomeKit 应用程序并在附加 HMAccessory 时出错

ios - Swift 中具有固定返回类型的子类 objc 数组中需要进行强制转换

ios - Swift:将一个对象数组和另一个对象数组保存到 NSUserDefaults 中