我有一个带有自定义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];


}

我的日志正确显示了所选按钮的值,但无法更改按钮的图像

感谢您的阅读。

最佳答案

尝试将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"]
        }
    }
}

09-19 10:40