如何向UITableViewCell添加复选框?

时间:2010-09-08 10:10:02

标签: iphone objective-c uitableview sdk

前一段时间有人已经问了这个问题并给出了一些答案,但我并不真正理解他们中的任何一个。所以我想知道是否有人可以写一个易于理解的教程,如何做下面图片所示的事情:

http://img208.yfrog.com/img208/6119/screenshotkmr.png

如果有人可以分享到如何做到这一点我真是太棒了,因为它看起来非常酷,我很乐意在我的应用程序中使用类似的东西: - )!

2 个答案:

答案 0 :(得分:31)

制作未选中且已选中的图片..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    if ([selectedRowsArray containsObject:[contentArray objectAtIndex:indexPath.row]]) {
        cell.imageView.image = [UIImage imageNamed:@"checked.png"];
    }
    else {
       cell.imageView.image = [UIImage imageNamed:@"unchecked.png"];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleChecking:)];
    [cell.imageView addGestureRecognizer:tap];
    cell.imageView.userInteractionEnabled = YES; //added based on @John 's comment
    //[tap release];

    cell.textLabel.text = [contentArray objectAtIndex:indexPath.row];
    return cell;
}

- (void) handleChecking:(UITapGestureRecognizer *)tapRecognizer {
    CGPoint tapLocation = [tapRecognizer locationInView:self.tableView];
    NSIndexPath *tappedIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation];

    if ([selectedRowsArray containsObject:[contentArray objectAtIndex:tappedIndexPath.row]]) {
        [selectedRowsArray removeObject:[contentArray objectAtIndex:tappedIndexPath.row]];
    }
    else {
        [selectedRowsArray addObject:[contentArray objectAtIndex:tappedIndexPath.row]];
    }
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:tappedIndexPath] withRowAnimation: UITableViewRowAnimationFade];
}

答案 1 :(得分:1)

我能想到的一种方法是你自定义UITableViewCell(this tutorial适合启动。这是another, similar one)。在自定义UITableViewCell内部,您需要在其中放置一个带有圆形图像的UIButton。当用户选择按钮时,您将图像更改为绿色圆圈

相关问题