IlludiumPu36 IlludiumPu36 - 5 months ago 72
Swift Question

Programmatically set image to UIImageView with XCode 6.1/Swift

I'm trying to set UIImageView programmatically in XCode 6.1:

@IBOutlet weak var bgImage: UIImageView!

var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)
bgImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(bgImage)


But Xcode is saying "expected declaration" with
bgImage = UIImageView(image: image)
Image
"afternoon"
is a PNG, and my understanding is PNG does not need an extension in XCode 6.1.

Also tried just
bgImage.image = UIImage(named: "afternoon")
, but still get:

enter image description here

UPDATE

OK, I have put the code to update
UIImageView
into the
viewDidLoad
function, but
UIImageView
is still not showing the image (which exists in the base directory as afternoon.png):

@IBOutlet weak var bgImage: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

updateTime()
var timer = NSTimer()
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)

var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)

}

Answer

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:). Ran this code and the image appeared fine since it the image was already assigned using the outlet.

enter image description here

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