2015-06-29 87 views
2

基本上,它是這樣的問題: How to detect touches on UIImageView of UITableViewCell object in the UITableViewCellStyleSubtitle style如何在Swift中檢測UITableViewCell的UIImageView上的觸摸?

但我必須在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); 
} 

有人可以幫助我移植此代碼嗎? 。:(

回答

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號線)斯威夫特使用true而不是YES積極Boolean
  • 線3)類型let tapped = UITapGestureRecognizer(插入到Xcode中,並查看彈出的自動完成選項。選擇targetaction。在目標self和行動"myFunction:"
  • 4號線)差不多相同的填充
  • 5號線)上cell.imageView
  • 6號線)中不需要調用addGestureRecognizer(tapped),ARC爲您完成此
  • 7號線),定義一個函數myFunction這需要一個名爲gestureUITapGestureRecognizer,並且不返回任何事情,因爲你已經照顧了,在你的函數
  • 10號線的頭不需要
  • 9號線)線)使用println代替NSLog和使用字符串插值打印出gesture.view.tag
+0

漂亮!最後擺脫了我的UIImage定製UIButton :)很多感謝隊友,在iOS 11/Swift 4中也能很好地工作。 – Maziyar

2

斯威夫特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") 
}