我使用了带有图片的自定义按钮。
通常情况下,当我们点击按钮时,按钮的颜色会改变。
当我点击这个自定义按钮时,我想要改变自定义按钮中的图片。
我该怎么做呢?
谢谢。
如果假设这是一个标准的UIButton,你可以在初始化按钮时执行以下操作:
[btnObj setImage:[UIImage imageNamed:@"imgName.png"] forState:UIControlStateHighlighted];
或者对于背景图片:
[btnObj setBackgroundImage:[UIImage imageNamed:@"imgName.png"] forState:UIControlStateHighlighted];
首先,将一个按钮作为您视图控制器的成员变量创建。 让我们称之为UIButton * myButton
。
然后,像这样初始化按钮,并将其图像设置为您想要显示的原始图像:
myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[myButton setImage:[UIImage imageNamed:@"OriginalImage"] forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(onClickMyButton) forControlEvents:UIControlEventTouchUpInside];
-(void) onClickMyButton
{
[myButton setImage:[UIImage imageNamed:@"NewImage"] forState:UIControlStateNormal];
}
看,问题解决了:)
首先在Storyboard中为按钮创建名为“btYesAction”和“btNoAction”的对象。
现在转到viewcontroller.m并粘贴以下代码
<pre>
(IBAction)btYesAction:(id)sender {
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
[button setImage:[UIImage imageNamed:@"NO1.png"]
forState:UIControlStateSelected];
if(![[NSUserDefaults standardUserDefaults]boolForKey:@"volume_control"]){
[btnVolume setImage:[UIImage imageWithIcon:@"fa-volume-up" backgroundColor:[UIColor clearColor] iconColor:clrPureBlueTint andSize:CGSizeMake(32, 32)] forState:UIControlStateNormal];
}else{
[btnVolume setImage:[UIImage imageWithIcon:@"fa-volume-off" backgroundColor:[UIColor clearColor] iconColor:[UIColor whiteColor] andSize:CGSizeMake(32, 32)] forState:UIControlStateNormal];
}
然后在点击事件中
- (void)btnVolumeClicked : (UIButton *)sender{
if ([[NSUserDefaults standardUserDefaults]boolForKey:@"volume_control"]) {
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"volume_control"];
[[NSUserDefaults standardUserDefaults] synchronize];
}else{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"volume_control"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
[self selectedState];}
-(void) selectedState{
if(![[NSUserDefaults standardUserDefaults]boolForKey:@"volume_control"]){
[btnVolume setImage:[UIImage imageWithIcon:@"fa-volume-up" backgroundColor:[UIColor clearColor] iconColor:clrPureBlueTint andSize:CGSizeMake(32, 32)] forState:UIControlStateNormal];
}else{
[btnVolume setImage:[UIImage imageWithIcon:@"fa-volume-off" backgroundColor:[UIColor clearColor] iconColor:[UIColor whiteColor] andSize:CGSizeMake(32, 32)] forState:UIControlStateNormal];
}}
我正在使用 Font Awesome,但你可以像这样简单地设置按钮图像
[btnVolume setImage:[UIImage imageNamed:@"NO1.png"]
forState:UIControlStateSelected];
Jose Rafael Santiago Jr.'s Answer 在 Swift 3 中:
yourButton.setImage(UIImage(named: "imgName"), for: .normal)
或者用于背景图片:
yourButton.setBackgroundImage(UIImage(named: "imgName"), for: .normal)