向UIViewController添加约束不起作用

时间:2019-05-26 18:22:05

标签: ios swift iphone

一个简单的问题,但我没有得到满意的答案。 因此,我想通过代码向我添加的UIViewController添加一些约束。

非常感谢您:)

override func viewDidLoad() {

let imageLogoName = "pictureIsInAssets"
let imageLogo = UIImage(named: imageLogoName)
let imageLogoView = UIImageView(image: imageLogo!)

setImageContraints()
}



func setImageContraints(){

imageLogoView.translatesAutoresizingMaskIntoConstraints = false
imageLogoView.widthAnchor.constraint(equalToConstant: 180).isActive = true
imageLogoView.heightAnchor.constraint(equalToConstant: 180).isActive = true
imageLogoView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageLogoView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
    }


在func setImageContraints中: 错误:使用无法解析的标识符“ imageLogoView”

2 个答案:

答案 0 :(得分:1)

您在可见性/生命周期范围之外使用变量imageLogoView。您应该改为使用实例变量:

class SomeViewController {
    var imageLogoView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad() // <-- notice this

        let imageLogoName = "pictureIsInAssets"
        let imageLogo = UIImage(named: imageLogoName)
        self.imageLogoView = UIImageView(image: imageLogo!)

        setImageContraints()
    }
}

或更简单:

class SomeViewController {
    let imageLogoView = UIImageView(image: UIImage(imageLiteralResourceName: "pictureIsInAssets"))

    override func viewDidLoad() {
        super.viewDidLoad() // <-- notice this

        setImageContraints()
    }
}

不要忘记将图像视图添加到视图中。

答案 1 :(得分:0)

imageLogoView不是全局变量。

您必须这样声明:

class ViewController: UIViewController{
   let imageLogoView: UIImageView!


   override func viewDidLoad() {

   let imageLogoName = "pictureIsInAssets"
   let imageLogo = UIImage(named: imageLogoName)
   imageLogoView = UIImageView(image: imageLogo!)

   setImageContraints()
   }
}