0

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.

Seyed Parsa Neshaei
  • 3,470
  • 18
  • 30
Tim B.
  • 21
  • 2

4 Answers4

3

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];
Jscti
  • 14,096
  • 4
  • 62
  • 87
Peppo
  • 1,107
  • 1
  • 12
  • 19
1

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];
 }
Desdenova
  • 5,326
  • 8
  • 37
  • 45
1

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
Tim B.
  • 21
  • 2
0

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

Satheesh
  • 10,998
  • 6
  • 50
  • 93