如何更改iOS上的button背景图像?

我在我的视图控制器上创build了一个button,它具有预定义的背景图像。 我为这个button创build了一个动作和一个sockets。 我想当用户点击button来改变这个button的背景图像。 我怎样才能做到这一点? 我试图把button的操作方法如下所示:

snapshotCheckbox.image = [UIImage imageNamed:@"snapshot.png"]; 

但我想这个方法是UImageViews。 我怎么能做一个button相同的东西? D.非常感谢您阅读我的文章:D

一个解决scheme就是在UIImageView显示图像,并在UIImageView放置一个透明的UIButton。 在界面生成器中,您可以将UIButton更改为“自定义”。 当处理UIButton被触发时所触发的动作时,这将允许您轻松地更改UIImageView中显示的图像。

希望这可以帮助。

您可以在viewDidLoad中设置button的给定状态的图像:

 [myButton setBackgroundImage:[UIImage imageNamed:@"myBackgroundImage.png"] forState:UIControlStateHighlighted]; 

一个button有两个properties imagebackgroundImage ..

用于setting image使用

 button.currentImage = image (or) [button setImage:image ForState:UIControlStateNormal]; 

用于setting backgroundImage使用

 button.currentBackgroundImage = image (or) [button setBackgroundImage:image ForState:UIControlStateNormal]; 

首先设置button的tybe

 button = [UIButton buttonWithType :UIButtonTypeCustom]; 

然后使用

  [button setImage:[UIImage imageNamed:@"imagename.type"] ForState:UIControlStateNormal]; 

在button对象上有setBackgroundImage:forState:方法。 请参阅在代码中设置UIButton的图像以获取更多信息(秒钟回答)。

另外,如果您为UIControlStateHighlighted状态设置图像(尽pipe只要用户一直按下button),UIButton会在按下时自动更改图像。

SETbutton

如果你点击时需要图像

 [snapshotCheckbox setImage:[UIImage imageNamed:@"snapshot.png"] forState:UIControlStateHighlighted]; 

或者如果你想select它后图像

 [snapshotCheckbox setImage:[UIImage imageNamed:@"snapshot.png"] forState:UIControlStateSelected]; 

并在onclick函数中提到

 snapshotCheckbox.Selected=YES; 

要在button上设置图像,只需在Main.storyboard中按下想要图像的button,然后在右侧的实用工具栏中按属性检查器 ,并将背景设置为所需的图像! 确保你在左边的支持文件中有你想要的图片。