setImage无法在UITableViewCell

时间:2016-02-01 02:08:43

标签: ios objective-c uitableview

我有UITableViewCell imageview作为" checkbox"点击后,它会checkuncheck。我在UITableViewCell

中有一个方法
-(void) toggleCheck {
    if(checked) {
        checked = NO;
        [self.imageView setImage:[UIImage imageNamed: @"empty-check.png"]];
    } else {
        checked = YES;
    [self.imageView setImage:[UIImage imageNamed: @"check.png"]];
    }
}

然后在我的ViewController中,我这样做:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        CheckCell *cell = (CheckCell *)[tableView dequeueReusableCellWithIdentifier:@"CheckCell"];
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CheckCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }

        [cell toggleCheck]; // check the box
    }
}

但是UIImageView图像并没有改变。我也尝试过[tableView reloadData]没有运气

有关为何不更新的任何想法?

3 个答案:

答案 0 :(得分:0)

只是尝试这样做...因为你正在访问委托方法之外的cell.imageView时图像可能没有设置

我也不确定你是否正在访问正确的图片。如果您正在使用self.imageView,则需要首先将imageView声明为@property。 这样做会给你带来麻烦,因为你在表格中的行数增加时重复使用表格单元格。

此处不需要编写单独的函数切换,因此您可以跳过它并将其写入didSelect方法

(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
           CheckCell *cell = (CheckCell *)[tableView dequeueReusableCellWithIdentifier:@"CheckCell"];
        if (cell == nil) 
        {
             NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CheckCell" owner:self options:nil];
             cell = [nib objectAtIndex:0];
        }
        if(checked) 
        {
           checked = NO;
           [cell.imageView setImage:[UIImage imageNamed: @"empty-check.png"]];
        }
        else 
        {
           checked = YES;
           [cell.imageView setImage:[UIImage imageNamed: @"check.png"]];
        }
    }

答案 1 :(得分:0)

您不应在didSelectRowAtIndexPath方法中创建新单元格 在方法中创建一个新单元是没有用的 您可以使用[yourtable cellForRowAtIndexPath:indexPath];来获取所选单元格 考虑此代码,例如

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        CheckCell *cell = (CheckCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell toggleCheck]; // check the box
    }
}

答案 2 :(得分:0)

您的实施存在问题。 checked状态不应该是UITableViewCell实例的一部分。它应该是您模型的一部分。请注意,表视图将重用您的单元格,因此在表视图单元格中维护已检查状态将无法按预期工作。您必须将已检查状态存储在模型中,并使用该模型的属性更新单元格检查状态。表视图单元格应仅用于绘制单元格而不维护任何状态,因为当表格中有许多单元格时,它将被重用。

相关问题