【问题标题】:UIImageView not displayingUIImageView 不显示
【发布时间】:2020-09-30 20:58:45
【问题描述】:

这是快速代码:

if let myImagePth = Bundle.main.path(forResource: "testImage", ofType: "jpg", inDirectory: "myImages"
{
        let myUIImage = UIImage(contentsOfFile: myImagePath)
        var myUIImageView = UIImageView(image: myUIImage)
        myUIImageView.center = self.view.center
}

我验证了“myUIImageView”确实有一个位置并且图像路径是正确的,但我不确定它为什么不显示。这段代码写在 viewcontroller 中。我开始认为它可能没有链接到视图控制器

【问题讨论】:

    标签: swift uikit


    【解决方案1】:

    你应该把它添加到视图并设置一个框架

    var myUIImageView = UIImageView(image: myUIImage)
    view.addSubView(myUIImageView)
    myUIImageView.frame = CGRect(x:0,y:0,width:100,height:100)
    myUIImageView.center = self.view.center
    

    【讨论】:

      【解决方案2】:

      问题是 ImageView 没有被添加到视图中。下面的代码将在视图控制器的中心显示图像。

      if let myImagePath = Bundle.main.path(forResource: "testImage", ofType: "jpg", inDirectory: "myImages") {
              let myUIImage = UIImage(contentsOfFile: myImagePath)
              let myUIImageView = UIImageView(image: myUIImage)
              
              myUIImageView.translatesAutoresizingMaskIntoConstraints = false
              view.addSubview(myUIImageView)
              myUIImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0).isActive = true
              myUIImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -50.0).isActive = true
          }
      

      【讨论】:

        猜你喜欢
        • 2018-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多