如何检测Swift中UITableViewCell的UIImageView上的触摸?

时间:2015-06-29 00:00:25

标签: swift

基本上,问题与此相同: How to detect touches on UIImageView of UITableViewCell object in the UITableViewCellStyleSubtitle style

但我必须在Swift中这样做。我无法在Obejctive-C中编程。

cell.imageView.userInteractionEnabled = YES;
cell.imageView.tag = indexPath.row;

UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myFunction:)];
tapped.numberOfTapsRequired = 1;
[cell.imageView addGestureRecognizer:tapped];   
[tapped release];


-(void)myFunction :(id) sender
{
UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;
NSLog(@"Tag = %d", gesture.view.tag);
}

有人可以帮我移植这段代码吗? :(

2 个答案:

答案 0 :(得分:4)

尝试自己写。这就是你学习的方式。以下是一些逐行提示:

1: cell.imageView.userInteractionEnabled = YES;
2: cell.imageView.tag = indexPath.row;

3: UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myFunction:)];
4: tapped.numberOfTapsRequired = 1;
5: [cell.imageView addGestureRecognizer:tapped];
6: [tapped release];


7: -(void)myFunction :(id) sender
8: {
9:     UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;
10:    NSLog(@"Tag = %d", gesture.view.tag);
11:}

提示

  • 丢失分号
  • 第1行)Swift使用true代替YES获得肯定Boolean
  • 第3行)在Xcode中输入let tapped = UITapGestureRecognizer(并查看弹出的自动完成选项。选择targetaction的那个。填写目标self和操作"myFunction:"
  • 第4行)非常相同
  • 第5行)在addGestureRecognizer(tapped)
  • 上致电cell.imageView
  • 第6行)不需要,ARC为你做这个
  • 第7行)定义一个myFunction函数,该函数调用UITapGestureRecognizer gesture并且不返回任何内容
  • 第9行)由于您已经在函数的标题中处理了
  • ,因此不需要行
  • 第10行)使用println代替NSLog并使用字符串插值打印gesture.view.tag

答案 1 :(得分:2)

Swift 3

cell.imageView.isUserInteractionEnabled = true
cell.imageView.tag = indexPath.row

let tapped = UITapGestureRecognizer(target: self, action: #selector(myFunction))
tapped.numberOfTapsRequired = 1
cell.imageView.addGestureRecognizer(tapped)



func myFunction(gesture: UITapGestureRecognizer) {
    print("it worked")
}