Tim B.
Tim B.

Reputation: 21

How to change the picture placed by UIImage

I placed an image on a button (group) and want to change it on button press. But I don't know how? Every code I find (UIImageVew, ...) relies on an image name!?

Thank you for a little hint.

Edit: What I forget to say is, that I am coding with WatchKit for watchOS 2.

Upvotes: 0

Views: 276

Answers (4)

Tim B.
Tim B.

Reputation: 21

Thanks for so many quick help!!! It seems, that I am not very keen in my first steps.

What I forget to say is, that I am coding with watchkit (for watchos2).

Inserting

UIButton* myButton = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];

Gives me "Unknow Identifier UIButton" within the

@implementation InterfaceController

or

@implementation InterfaceController

Upvotes: 1

Muhammad Awais
Muhammad Awais

Reputation: 108

If you want to change the image when the button is clicked, you can do like this:

-(IBAction)buttonClicked: (id)sender
 {   
     UIButton *buttonObj = (UIButton*)sender;
     [buttonObj setBackgroundImage:[UIImage imageNamed:@"myImage.png"]  forState:UIControlStateNormal];
 }

Upvotes: 1

Peppo
Peppo

Reputation: 1113

You create the button (with frame):

UIButton* myButton = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];

you put the button image:

[myButton setImage:@"normalImage" forState:UIControlStateNormal];

And change the image when the button is pressed:

[myButton setImage:@"pressImage" forState:UIControlStateHighlighted];

Upvotes: 3

Satheesh
Satheesh

Reputation: 11276

Okay its pretty easy on the button press event method add the below statement,

[self.yourButtonObject setBackgroundImage:[UIImage imageNamed:"yourImage"] forControlState: UIControlStateNormal]

self.yourButtonObject is the outlet that you created for the button. Creating an outlet is like below.enter image description here

Upvotes: 0

Related Questions