2012-07-06 83 views
0

因此,我試圖在這裏構建某種待辦事項列表 - 我有一個表格視圖,每個單元格上都有一個代表複選框的縮略圖。接觸時,我希望它能夠改變圖像 - 從完整到空白,反之亦然。我做錯了什麼?下面是一些代碼:iOS 5 - 更改觸摸的表格視圖單元格的縮略圖

- (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]; 
    } 
} 

}

回答

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]; 
} 
+0

它不工作:(我得到了很多重疊的縮略圖 – nemesis 2012-07-06 12:00:05

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]; 
    } 
相關問題