简体   繁体   English

如何更改UIImage放置的图片

[英]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!? 我找到的每个代码(UIImageVew,...)都依赖于图像名称!

Thank you for a little hint. 谢谢你的提示。

Edit: What I forget to say is, that I am coding with WatchKit for watchOS 2. 编辑:我忘了说的是,我正在使用WatchKit 2的WatchKit进行编码。

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). 我忘了说的是,我正在用watchkit编码(用于watchos2)。

Inserting 插入

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

Gives me "Unknow Identifier UIButton" within the 给我“未知标识符UIButton”

@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 setBackgroundImage:[UIImage imageNamed:“ yourImage”] forControlState:UIControlStateNormal]

self.yourButtonObject is the outlet that you created for the button. self.yourButtonObject是您为按钮创建的插座。 Creating an outlet is like below. 创建出口如下所示。 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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