简体   繁体   中英

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.

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];

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];
 }

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

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. 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM