Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJose A Ocando Jose A Ocando
1,482 PointsHow do you create a button that changes images when selected?
Hey all! I'm not sure this is the best place for this question, but I thought the community here would be the perfect guide. I'm trying to create a radio button for an app I'm building after completing the weather app. My thought was that I needed an IBOutlet in viewController.swift and then an IBAction.
Here's the IBOutlet
@IBOutlet weak var radioButtonOne: UIButton!
and the IBAction
@IBAction func pushedButtonOne() {
radioButtonOne.setImage("buttonPushed": UIImage?, forState: UIControlStateSelected)
}
radioButtonOne is the name of the button itself and button Pushed is the name of the image.
I get two errors:
Expected "," separator and Expected expression in list of expressions
Side note: I have tried storing the images in the button's inspector field in main.storyboard. I stored an "unpresssed" version of the button in the default state and a "pressed" version of the button in the Selected state. But, when I run the app simulator, the button doesn't change images...
Any ideas?
2 Answers
Aaron Watkins
10,902 PointsHi! I'm thinking it might be like this.
@IBAction func pushedButtonOne() {
let image = UIImage(named: "buttonPushed") as UIImage
radioButtonOne.setImage(image, forState: UIControlState.Normal)
}
At least this is the way I've done it before. Hope this helps.
Jose A Ocando Jose A Ocando
1,482 PointsPerfect!
I had to add a bang operator to the "as UIImage", so it ended up looking like:
let pressedButtonImage = UIImage(named: "radioPushed") as UIImage! radioButtonOne.setImage(pressedButtonImage, forState: UIControlState.Normal)
Thanks Aaron! That was awesome.
Aaron Watkins
10,902 Pointsno problem at all. good luck!