Programmatically Set Image to Uiimageview with Xcode 6.1/Swift

Programmatically set image to UIImageView with Xcode 6.1/Swift

Since you have your bgImage assigned and linked as an IBOutlet, there is no need to initialize it as a UIImageView... instead all you need to do is set the image property like bgImage.image = UIImage(named: "afternoon"). After running this code, the image appeared fine since it was already assigned using the outlet.

Sample Image

However, if it wasn't an outlet and you didn't have it already connected to a UIImageView object on a storyboard/xib file, then you could so something like the following...

class ViewController: UIViewController {
var bgImage: UIImageView?

override func viewDidLoad() {
super.viewDidLoad()

var image: UIImage = UIImage(named: "afternoon")!
bgImage = UIImageView(image: image)
bgImage!.frame = CGRectMake(0,0,100,200)
self.view.addSubview(bgImage!)
}
}

how to programmatically, in Swift, set an uiimageview to the xcode built-in applewatch icon image?

You seem to be talking about the SF symbol applewatch. You can get that (or any other SF symbol) by using UIImage(systemName:):

UIImage(systemName: "applewatch")

Notes:

  • The color of the watch depends on the tintColor of the image view
  • Available on iOS 14+

How to add image in a xib view controller (swift3)

Assuming your UIImageView is named imageView and that your image is named "MyImage.jpg", you do this:

let theImage = UIImage(named: "MyImage.jpg") // create a UIImage
imageView.image = theImage // UIImageView takes a UIImage

Also note, UIImage(named:) is (1) case-sensitive and will result in a null image if not found, and (2) if your image is a PNG you do not need the file type.

One last note, if you misspell the image file and UIImage is null? The error will happen on the second line of code, not the first.

How do I set a background image using Xcode?

Go to your storyboard, and find this button at the bottom left corner:

Sample Image

You should see this on your left now:

Sample Image

Now drag your image view object under any other object you wish on the left hand side under your view controller scene. An example would be that if you had this persons objects in your view controller you would put the image view before the button.

Hope this helped.



Related Topics



Leave a reply



Submit