如何在触摸时更改一个UITableViewCell

时间:2011-12-12 22:18:11

标签: objective-c ios uitableview

我有一个包含多个图像的表格视图单元格。当触摸图像时,它们会在图像顶部显示一个叠加层,告诉用户该图像已被选中。

有没有办法改变一个UITableViewCell的外观,而不必执行[tableView reloadData],这将允许我在表视图数据源委托方法中以不同方式设置单元格样式。

2 个答案:

答案 0 :(得分:1)

我这样做的方法是继承UITableViewCell,然后在tableView:didSelectRowAtIndexPath:上获取对单元格的引用并做任何你想做的事情(或者只是针对图像触摸事件,如果这不是选择)。

可能有另一种方法可以在不必子类化的情况下执行此操作,但我发现自己一直在为UITableViewCell创建子类,这非常简单。

答案 1 :(得分:1)

如果您希望避免子类化,可以使用手势识别器来实现。您的问题建议在每个图像上点击并按住用户交互,我已在下面的代码中实现了这一点。需要记住的一点是,如果用户点击并按住,他们可能看不到您希望他们看到的文本。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"ImageCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (!cell) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}

UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];

 UILongPressGestureRecognizer *recognizer2 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Ben.png"]];
imageView.frame = CGRectMake(cell.contentView.bounds.origin.x,cell.contentView.bounds.origin.y , 100, 40);
imageView.userInteractionEnabled = YES;
[imageView addGestureRecognizer:recognizer];
[cell.contentView addSubview:imageView];

UIImageView *imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Steve.png"]];
imageView2.frame = CGRectMake(cell.contentView.bounds.origin.x + imageView.frame.size.width + 10,cell.contentView.bounds.origin.y , 100, 40);
imageView2.userInteractionEnabled = YES;
[imageView2 addGestureRecognizer:recognizer2];
[cell.contentView addSubview:imageView2];

[imageView release];
[imageView2 release];
[recognizer release];
[recognizer2 release];

return cell;}



- (void)imageTapped:(id)sender {
    NSLog(@"%@", sender);

    UILongPressGestureRecognizer *recognizer = (UILongPressGestureRecognizer *)sender;

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        UILabel *label = [[UILabel alloc] initWithFrame:recognizer.view.bounds];
        label.text = @"Pressed";
        label.backgroundColor = [UIColor clearColor];
        label.tag = 99999;
        label.textColor = [UIColor whiteColor];
        [recognizer.view addSubview:label];
        [label release];
    }
    else {
        [[recognizer.view viewWithTag:99999] removeFromSuperview];
    }
}

希望这有帮助。