How do you create a UIImage View Programmatically - Swift

前端 未结 8 1607
梦如初夏
梦如初夏 2020-12-02 04:23

I\'m trying to create a UIImage View programmatically, I have a new view and I tried doing this

let imageName = \"yourImage.png\"
yourview.backgroundColor =          


        
8条回答
  •  有刺的猬
    2020-12-02 05:06

    This answer is update to Swift 3.

    This is how you can add an image view programmatically where you can control the constraints.

    Class ViewController: UIViewController {
    
        let someImageView: UIImageView = {
           let theImageView = UIImageView()
           theImageView.image = UIImage(named: "yourImage.png")
           theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
           return theImageView
        }()
    
        override func viewDidLoad() {
           super.viewDidLoad()
    
           view.addSubview(someImageView) //This add it the view controller without constraints
           someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints
        }
    
        // do not forget the `.isActive = true` after every constraint
        func someImageViewConstraints() {
            someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
            someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
            someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
            someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
        }
    
    }
    

提交回复
热议问题