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 =
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
}
}
Thanks, MEnnabah, just to add to your code where you are missing the =
sign in the declaration statement:
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
}()
Everything else is, all perfect for Swift 3.
In 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)
You can use above in one line.
let imageView = UIImageView(image: UIImage(named: "yourImage.png")!)
First you create a UIImage
from your image file, then create a UIImageView
from that:
let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
Finally you'll need to give imageView
a frame and add it your view for it to be visible:
imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(imageView)
Swift 4:
First create an outlet for your UIImageView
@IBOutlet var infoImage: UIImageView!
Then use the image property in UIImageView
infoImage.image = UIImage(named: "icons8-info-white")