自定义表格视图单元格按钮在tableview reloadData之后保持选中状态

时间:2015-01-25 00:40:43

标签: ios objective-c uitableview

当我重新加载我的tableView时,我的自定义单元格按钮不会重新加载到其初始状态。我想让检查返回“plusImage”。知道为什么这不起作用吗? reloadData是否会调用新的重用单元格?

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ReusableIdentifier = @"Cell";
    SetListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReusableIdentifier forIndexPath:indexPath];


    cell.delegate = self;



            UIImage *checkImage = [UIImage imageNamed:@"check.png"];
            UIImage *plusImage  = [UIImage imageNamed:@"plusButton"];



            if ([self.selectedRows containsIndex:indexPath.row]) {
                [cell.plusButton setBackgroundImage:checkImage forState:UIControlStateNormal];
            }
            else {
                [cell.plusButton setBackgroundImage:plusImage forState:UIControlStateNormal];
            }
            cell.tag = indexPath.row;





    return cell;
}

当单元格准备好重新使用时

-(void)prepareForReuse
{
    UIImage *plusImage = [UIImage imageNamed:@"plusImage"];
    [self.plusButton setBackgroundImage:plusImage forState:UIControlStateNormal];
    self.plusButton.enabled = YES;

    [super prepareForReuse];
}

1 个答案:

答案 0 :(得分:0)

以下是如何使用UIButton的状态:

在界面构建器或自定义类中(在这种情况下:SetListTableViewCell,虽然我建议更改该名称),您应该为不同的状态设置按钮的背景图像:UIControlStateNormal& UIControlStateHighlighted。然后将按钮的状态设置为“正常”或“突出显示”。所以在SetListTableViewCell.m

- (void)awakeFromNib
{
    [super awakeFromNib];

    [self.plusButton setBackgroundImage:[UIImage imageNamed:@"plusImage"] forState:UIControlStateNormal];
    [self.plusButton setBackgroundImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateHighlighted];

}

-(void)prepareForReuse
{
    [super prepareForReuse];

    self.plusButton.highlighted = NO;
}

然后:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ReusableIdentifier = @"Cell";
    SetListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReusableIdentifier forIndexPath:indexPath];

    cell.delegate = self;
    [cell.plusButton setHighlighted: [self.selectedRows containsIndex:indexPath.row]];
    cell.tag = indexPath.row;

    return cell;
}

如果您正在使用TableView的选择,那么您甚至可以使用:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
    self.plusButton.highlighted = selected;
}
相关问题