iOS 5 - 在触摸时更改表格视图单元格的缩略图

时间:2012-07-06 11:20:43

标签: ios5 uitableview thumbnails

所以我试图在这里构建一些待办事项列表 - 我有一个表格视图,并且在每个单元格上我都有一个代表复选框的缩略图。在触摸时,我希望它能够改变图像 - 从完全变为空,反之亦然。我做错了什么?这是一些代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"taskCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 32, 32)];
[button addTarget:self action:@selector(checkmarkPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:[UIImage imageNamed:@"checkbox_empty"] forState:UIControlStateNormal];
[button setTag:101];
[cell addSubview:button];
[cell setIndentationWidth:36];
[cell setIndentationLevel:1];
cell.textLabel.text = [[self.appDel.allTasks objectAtIndex:indexPath.row] taskName];
return cell;

}

- (void) checkmarkPressed:(UIButton *)sender{
if(sender.tag == 101){
    UITableViewCell *cell = ((UITableViewCell*)[sender superview]);
    NSLog(@"Cell %i", [self.tableView indexPathForCell:cell].row);
    UIImage *empty = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"checkbox_empty" ofType:@"png"]];
    UIImage *full = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"checkbox_full" ofType:@"png"]];
    if ([sender imageView].image == [UIImage imageNamed:@"checkbox_empty"]) {
        [sender setImage:full forState:UIControlStateNormal];
        [self.tableView reloadData];
    }
    if ([sender imageView].image == full) {
        [sender setImage:empty forState:UIControlStateNormal];
        [self.tableView reloadData];
    }
}

}

2 个答案:

答案 0 :(得分:0)

如果您只想在触摸时更改图像,可以尝试使用此代码

- (void) checkmarkPressed:(UIButton *)tempButton{
    if (tempButton.tag == 101) {
        tempButton.tag = 104;
        [sender setImage:full forState:UIControlStateNormal];
    }
    else if (tempButton.tag == 104) {
        tempButton.tag = 101;
        [sender setImage:empty forState:UIControlStateNormal];
    }
    [self.tableView reloadData];
}

答案 1 :(得分:0)

找到解决方案:

if ([sender imageView].image == [UIImage imageNamed:@"checkbox_empty"]) {
        [sender removeFromSuperview];
        [sender setImage:full forState:UIControlStateNormal];
        [[sender superview] addSubview:sender];
        [self.tableView reloadData];
    }
    else if ([sender imageView].image == [UIImage imageNamed:@"checkbox_full"]) {
        [sender removeFromSuperview];
        [sender setImage:empty forState:UIControlStateNormal];
        [[sender superview] addSubview:sender];
        [self.tableView reloadData];
    }