Reputation: 315
So I am trying to load a picture programmatically using Swift and I am having some trouble. I can change the UIImage of a view using the Attributes Inspector, so I know the picture I am using is added properly and I am using the right name.
Here is the code I am using:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myPicture: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
myPicture.image = UIImage(named:"myNewPic")
}
}
I think there might be some setting I am missing in Attributes inspector or something since the code is pretty simple and I know the image is added properly.
Any help would be appreciated.
Upvotes: 0
Views: 97
Reputation: 27428
Make sure that your image name is correct. You have image properly in xcode and your outlet is properly connected
add image with extension if you are not using assets for images. like myNewPic.png
or myNewPic.jpg
whatever extension it is.
So, your code should be like,
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myPicture: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
myPicture.image = UIImage(named:"myNewPic.png") //or .jpg or else
}
}
another choice
if you load image from assets usemyNewPic
if you load from bundle use myNewPic.png
(with extensions).
if let img = UIImage(named: "myNewPic") {
myPicture.image = img
} else {
myPicture.image = UIImage(named:"myNewPic.Imageextensions")
}
Upvotes: 4