soulrain soulrain - 6 months ago 17
iOS Question

Changing an image using swift for iOS App

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.

Answer

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