我很难更改表格视图单元格中包含的UIButton
图像。我的代码如下:
// In tableview for cell at rowIndex method
self.iconBtn = [[UIButton alloc]initWithFrame:CGRectMake(670,10,80, 80)];
self.iconBtn.tag = kIconValueTag;
[cell.contentView addSubview:self.iconBtn];
//Add icon to cell
UIImage *btnImage = [UIImage imageNamed:@"blank_star.png"];
[self.iconBtn setImage:btnImage forState:UIControlStateNormal];
// I am calling method changeIconState after user clicks on icon.
[self.iconBtn addTarget:self action:@selector(changeIconState) forControlEvents:UIControlEventTouchUpInside];
按下按钮后,将调用表视图方法之外的方法:
-(void)changeIconState
{
if (self.iconSelectState == kIconNotSelected)
{
self.iconSelectState = kIconSelected;
}
else
{
self.iconSelectState = kIconNotSelected;
}
[self changeIcon];
}
-(void)changeIcon
{
if (self.iconSelectState == kIconSelected)
{
UIImage *btnImageHighlighted = [UIImage imageNamed:@"star.png"];
[self.iconBtn setImage:btnImageHighlighted forState:UIControlStateNormal];
}
else
{
UIImage *btnImageNormal = [UIImage imageNamed:@"blank_star.png"];
[self.iconBtn setImage:btnImageNormal forState:UIControlStateNormal];
}
}
运行程序后,图标没有按照我的要求从空白更改为星标。它只是一个空白的明星。我在这里错过了什么吗?
答案 0 :(得分:1)
为什么要自己管理图像/按钮状态?为什么不为定义的状态加载两个图像并让操作系统处理它?
//Add icon to cell
UIImage *btnImage = [UIImage imageNamed:@"blank_star.png"];
UIImage *btnImageHighlighted = [UIImage imageNamed:@"star.png"];
[self.iconBtn setImage:btnImage forState:UIControlStateNormal];
[self.iconBtn setImage:btnImageHighlighted forState:(UIControlStateHighlighted && UIControlStateSelected)];
如果您需要管理您的财产(iconSelectedState),您可以不用担心图像。或者,您可以查询按钮状态属性以确定它所处的状态。