在我的应用程序中,我有一个带有个人资料图片和用户名标签的tableview。如果单击其中一个,则需要执行此功能:
func goToProfileScreen(gesture: UITapGestureRecognizer) {
self.performSegueWithIdentifier("profile", sender: nil)
}
但是如果我尝试在我的cellForRowAtIndexPath中实现它,它只适用于我最后一次添加它。
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()
}
}
所以现在它适用于用户名标签。如果我将usernamelabel放在代码中,然后是profileImg,那么它只适用于profileImg?
我怎样才能让它们同时适用于它们?
答案 0 :(得分:0)
您需要使用2个不同的tapRecognizer,因为UITapGestureRecognizer只能附加到一个视图。 (“它们是您附加到 a 视图”的对象,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)