3

I am attempting something relatively simple. I have a UIButton that loads with an image:

@IBOutlet var peer5Outlet: UIButton!

    override func viewDidLoad() {
    super.viewDidLoad()

    peer5Outlet.enabled = true
    var img = UIImage(named: "camera")
    peer5Outlet.setImage(UIImage(named: "camera"),forState: UIControlState.Normal) }

Once it is loaded, I simply want to update that image by calling a method:

func updateButtonImage() {

    peer5Outlet.imageView!.image = UIImage(named: "connected")!

    print("peer5Outlet.imageView!.image = \(peer5Outlet!.imageView!.image!)")

}

However, I am still unable to update the image; the original image never changes in the view.

Perhaps I am missing some sort of view reload method?

Rashwan L
  • 38,237
  • 7
  • 103
  • 107

3 Answers3

3

Update your updateButtonImage function to

func updateButtonImage() {
    peer5Outlet.setImage(UIImage(named: "connected"), forState: .Normal)
    print("peer5Outlet.imageView!.image = \(peer5Outlet!.imageView!.image!)")
}
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • Thank you - that worked. But let me trouble you for one more question - and forgive me if this is more appropriate for a separate post: My hope is to change the UIButton image from different class (Swift file). I do this by calling the method this way (SendSoundsViewControlller() is the VC with the method): SendSoundsViewController().updateButtonImage() But when I do this, the compiler tells me my UIButton is nil: fatal error: unexpectedly found nil while unwrapping an Optional value – Charlie Stephenson Jan 04 '16 at 23:41
  • That´s why it´s a different instance of the viewController. I can really recommend a new question or make a search there is a lot of posts at SO for this issue. – Rashwan L Jan 04 '16 at 23:42
  • @CharlieStephenson here is a way you could do that http://stackoverflow.com/a/25204814/5576310 – Rashwan L Jan 04 '16 at 23:58
  • Ah, thank you. I will give this a try. Really appreciate it. – Charlie Stephenson Jan 06 '16 at 01:53
  • Np, did the above solution work for you @CharlieStephenson? – Rashwan L Jan 06 '16 at 02:02
3

Try

peer5Outlet.setBackgroundImage(UIImage(named: "connected"), forState: UIControlState.Normal)

Edit: In order to use the setImage method, you need to change the button's type to "Custom"...

Sotiris Kaniras
  • 520
  • 1
  • 12
  • 30
0

You need to use the main thread whenever you're touching UIImage on UI

GCD - main vs background thread for updating a UIImageView

func updateButtonImage() {
    dispatch_async(dispatch_get_main_queue()) {
        // update image
    }
}
Community
  • 1
  • 1
Tikhonov Aleksandr
  • 13,945
  • 6
  • 39
  • 53