无法以编程方式将 UIImageView 添加为 UIView 的子视图



我有一个单视图应用程序。 我有一个 UIView,它将 X 和 Y 居中到超级视图。 我正在尝试使用自动布局以编程方式作为 UIImageview 到 UIView。 我的图像无法显示在 UIView 中的任何位置。

@IBOutlet weak var popUpContainer: UIView!
let image = UIImage.init(named: "tickok")
let imageView = UIImageView.init(image: image)
self.popUpContainer.addSubview(imageView)
// THIS ENABLES THE AUTOLAYOUT CONSTRAINT FOR IMAGEVIEW
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.centerXAnchor.constraint(equalTo: self.popUpContainer.centerXAnchor).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 30).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 30).isActive = true
imageView.topAnchor.constraint(equalTo: self.popUpContainer.topAnchor, constant: 20).isActive = true

您还需要包含 Y 约束 - X、宽度和高度不足以进行自动布局。所以要么centerYAnchor,要么topAnchorbottomAnchor.

例如,包括imageView.centerYAnchor.constraint(equalTo: self.popUpContainer.centerYAnchor).isActive = true

最新更新