首页 > 解决方案 > 无法以编程方式将 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

标签: iosswiftautolayout

解决方案


您还需要包含 Y 约束 - X、宽度和高度对于自动布局来说是不够的。所以 要么centerYAnchor要么topAnchor要么bottomAnchor

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


推荐阅读