adams.s adams.s - 6 months ago 31
Swift Question

2 items in a cell with same tapGestureRecognizer (swift)

in my app i have a tableview with a profile image and a username label. If you click on one of the 2 then the need to do this function:

func goToProfileScreen(gesture: UITapGestureRecognizer) {
self.performSegueWithIdentifier("profile", sender: nil)
}


however if i try to implement this in my cellForRowAtIndexPath it only works for the last time i've added it.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell") as? NewsCell {
let post = self.posts[indexPath.row]

cell.request?.cancel()

let profileTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(NewsVC.goToProfileScreen(_:)))
profileTapRecognizer.numberOfTapsRequired = 1
// profileTapRecognizer.delegate = self

cell.profileImg.tag = indexPath.row
cell.profileImg.userInteractionEnabled = true
cell.profileImg.addGestureRecognizer(profileTapRecognizer)

cell.usernameLabel.tag = indexPath.row
cell.usernameLabel.userInteractionEnabled = true
cell.usernameLabel.addGestureRecognizer(profileTapRecognizer)

var img: UIImage?

if let url = post.profileImageURL {
if url != "" {
img = NewsVC.imageCache.objectForKey(url) as? UIImage
}
}

cell.configureCell(post, img: img)
cell.selectionStyle = .None

return cell

} else {

return NewsCell()
}
}


so now it works for the username label. if i put the usernamelabel first in the code and then the profileImg, then it only works for the profileImg?

how can i get it to work for both of them?

Answer

You need to use 2 different tapRecognizers, because a UITapGestureRecognizer can only be attached to one view. ("They are objects that you attach to a view", Apple Doku)

let profileTapRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(NewsVC.goToProfileScreen(_:)))
let profileTapRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(NewsVC.goToProfileScreen(_:)))
profileTapRecognizer1.numberOfTapsRequired = 1
profileTapRecognizer2.numberOfTapsRequired = 1

// profileTapRecognizer1.delegate = self
// profileTapRecognizer2.delegate = self

cell.profileImg.tag = indexPath.row
cell.profileImg.userInteractionEnabled = true
cell.profileImg.addGestureRecognizer(profileTapRecognizer1)

cell.usernameLabel.tag = indexPath.row
cell.usernameLabel.userInteractionEnabled = true
cell.usernameLabel.addGestureRecognizer(profileTapRecognizer2)
Comments