plasmid0h
plasmid0h

Reputation: 206

How to detect touches on UIImageView of UITableViewCell in Swift?

Basically, it is the same question as this : How to detect touches on UIImageView of UITableViewCell object in the UITableViewCellStyleSubtitle style

But i have to do it in Swift. I can't program in 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);
}

Can somebody help me to port this code ? :(

Upvotes: 2

Views: 2249

Answers (2)

dmyma
dmyma

Reputation: 223

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")
}

Upvotes: 2

vacawama
vacawama

Reputation: 154513

Try writing it yourself. That is how you learn. Here are some line by line hints:

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:}

Hints

  • Lose the semicolons all around
  • Line 1) Swift uses true instead of YES for a positive Boolean
  • Line 3) Type let tapped = UITapGestureRecognizer( into Xcode and look at the choices that pop up for autocomplete. Chose the one with target and action. Fill in target self and action "myFunction:"
  • Line 4) Pretty much identical
  • Line 5) Call addGestureRecognizer(tapped) on cell.imageView
  • Line 6) Not needed, ARC does this for you
  • Line 7) Define a function myFunction that takes a UITapGestureRecognizer called gesture and doesn't return anything
  • Line 9) Line not needed since you already took care of that in the header of your function
  • Line 10) Use println instead of NSLog and use string interpolation to print out gesture.view.tag

Upvotes: 4

Related Questions