我有自定义UITableView
自定义UITableViewCell
,其中包含UIButton
我希望在用户选择按钮时更改所选按钮的背景图片,
不幸的是,每当我按下它时图像都没有改变状态,它显示:
由于未捕获的异常而终止应用 'NSInvalidArgumentException',原因:' - [UIView 了setBackgroundImage:forState:]:
以下是我的代码段:
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *CellIdentifier = @"BTSTicketsCellIdentifier";
CRIndCategCell *cell = (CRIndCategCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
//Initialize cell
}
cell.favBtn.tag=indexPath.row;
[cell.favBtn addTarget:self action:@selector(AddToFav:) forControlEvents:UIControlEventTouchUpInside];
...
...
...
}
-(IBAction)AddToFav:(id)sender{
NSLog(@"Value of selected button = %ld",(long)[sender tag]);
UIButton *Btn=(UIButton*)[self.view viewWithTag:(long)[sender tag]];
[Btn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
[Btn setBackgroundImage:[UIImage imageNamed:@"grey-star.png"] forState:UIControlStateNormal];
}
我的日志正确显示所选按钮的值但无法更改按钮的图像
感谢您阅读。
答案 0 :(得分:4)
尝试将AddToFav:
方法修改为:
-(IBAction)AddToFav:(UIButton *)sender{
NSLog(@"Value of selected button = %ld",(long)[sender tag]);
[sender setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
[sender setBackgroundImage:[UIImage imageNamed:@"grey-star.png"] forState:UIControlStateNormal];
}
或者使用它:
-(IBAction)AddToFav:(UIButton *)sender{
NSLog(@"Value of selected button = %ld",(long)[sender tag]);
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for (UIButton *btn in [cell.contentView.superview subviews] ) {
if ([btn isKindOfClass:[UIButton class]]&& btn.tag ==(long)[sender tag]) {
[btn setBackgroundImage:[UIImage imageNamed:@"grey-star.png"]
}
}
}
答案 1 :(得分:0)
检查按钮的标签是否== 0.这是UITableViewCell的contentView的默认标签,您可能正在尝试更改单元格内容的图像。