如何以编程方式创buildUIImage View – Swift

我试图创build一个UIImage视图编程,我有一个新的看法,我试图做到这一点

let imageName = "yourImage.png" yourview.backgroundColor = UIColor.colorWithPatternImage(UIImage(named:imageName)) 

这不起作用,因为我不知道这应该是的第二行。

问题:如何使UIImageView在屏幕上显示,而不是在故事板中进行编码

首先你从图像文件创build一个UIImage ,然后创build一个UIImageView

 let imageName = "yourImage.png" let image = UIImage(named: imageName) let imageView = UIImageView(image: image!) 

最后,你需要给imageView一个框架,并添加它的视图,使其可见:

 imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200) view.addSubview(imageView) 

首先创buildUIImageView,然后在UIImageView中添加图像。

  var imageView : UIImageView imageView = UIImageView(frame:CGRectMake(10, 50, 100, 300)); imageView.image = UIImage(named:"image.jpg") self.view.addSubview(imageView) 

这个答案是Swift 3的更新。

这是如何以编程方式添加图像视图,您可以控制约束。

 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 } } 

你可以在上面用一行。

  let imageView = UIImageView(image: UIImage(named: "yourImage.png")!) 

谢谢,MEnnabah,只是添加到你的代码中,你在声明声明中缺less=标志:

 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 }() 

其他的都是Swift 3的完美版本。

在Swift 3.0中:

 var imageView : UIImageView imageView = UIImageView(frame:CGRect(x:10, y:50, width:100, height:300)); imageView.image = UIImage(named:"Test.jpeg") self.view.addSubview(imageView)