我建议将手势识别器连接到UIImageView
自定义单元格的 init 方法中:
// Add recognizer for tappable image
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(imageViewTapped:)];
[tapRecognizer setNumberOfTouchesRequired:1];
[tapRecognizer setDelegate:self];
self.tappableImageView.userInteractionEnabled = YES;
[self.tappableImageView addGestureRecognizer:tapRecognizer];
然后处理程序:
- (void)imageViewTapped:(id)sender {
NSLog(@"image tapped");
self.tappableImageView.image = [UIImage imageNamed:@"some_different_image.png"];
}
另外,不要忘记像这样装饰自定义单元格声明:
@interface CustomTableViewCell : UITableViewCell <UIGestureRecognizerDelegate>
在该cellForRowAtIndexPath:
方法中,您需要确保您的 init 方法中的代码被触发以便tapRecognizer
添加。
祝你好运!
[编辑]
根据您使用自定义 XIB 创建单元格的方式,您可能不需要它,但在我的情况下,我需要显式调用一个方法来初始化表格单元格中 UI 的状态。我这样做的initState
方法是在自定义表格视图单元格上提供一种方法:
- (void)initState {
// Do other things for state of the UI in table cell.
// Add recognizer for tappable image
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(imageViewTapped:)];
[tapRecognizer setNumberOfTouchesRequired:1];
[tapRecognizer setDelegate:self];
self.tappableImageView.userInteractionEnabled = YES;
[self.tappableImageView addGestureRecognizer:tapRecognizer];
}
然后,cellForRowAtIndexPath
我确保initState
在创建表格单元格后调用它:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CustomTableViewCell *cell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
UIViewController *temporaryController = [[UIViewController alloc] initWithNibName:@"CustomTableViewCell" bundle:nil];
// Grab a pointer to the custom cell.
cell = (CustomTableViewCell *)temporaryController.view;
[cell initState];
}
return cell;
}