[英]change the background image of button in objective-c?
我在我的VC中的UITableView
单元格上有一个UIButton
arrowBtnUp = [UIButton buttonWithType:UIButtonTypeCustom];
arrowBtnUp.frame = CGRectMake(50,(65-19)/2,31, 31);
[arrowBtnUp setBackgroundImage:[UIImage imageNamed:@"arrow_up.png"] forState:UIControlStateNormal];
[arrowBtnUp addTarget:self action:@selector(slideAction) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:arrowBtnUp];
这是我的slideAction
-(void) slideAction
{
[arrowBtnUp setBackgroundImage:[UIImage imageNamed:@"arrow_down.png"] forState:UIControlStateNormal];
// also tried with UIControlStateSelected/Highlighted
}
但是它没有用,我找到了这个链接但是没有帮助。 任何建议或样品将不胜感激。
您的代码应该可以工作。无论如何都要这样更改代码并尝试
-(void) slideAction:(id)sender
{
[sender setBackgroundImage:[UIImage imageNamed:@"arrow_down.png"] forState:UIControlStateNormal];
}
和
[arrowBtnUp addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventTouchUpInside];
并确保您的应用程序包中包含arrow_down.png
问题是您正在重用UIButton的arrowBtnUp
实例。 因此,在slideAction
方法中,您将不会获得按下按钮的引用。
为了在slideAction
方法中获取引用,您需要将其作为参数传递。
因此,更改代码如下:
[arrowBtnUp addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventTouchUpInside];
-(void) slideAction:(UIButton *)myButton
{
[myButton setBackgroundImage:[UIImage imageNamed:@"arrow_down.png"] forState:UIControlStateNormal];
}
如果尝试在触摸后更改按钮图像,则应使用UIButton的控件状态。 您可以为每个“状态”分配背景图像,然后让UIButton确定显示哪个图像。
背景图像与按钮上的图标不同。 尝试以下方法:
[_buttonConfirm setImage:[UIImage imageNamed:@"s.png"] forState:UIControlStateNormal];
如果尝试在触摸后更改按钮图像,则应使用UIButton的控件状态。 您可以为每个“状态”分配背景图像,然后让UIButton确定显示哪个图像。
[myButton setBackgroundImage:[UIImage imageNamed:@"arrow_up.png"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"arrow_down.png"] forState:UIControlStateSelected];
无需在slideAction:target方法中手动切换背景图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.