gpt4 book ai didi

swift - 单元格中的 2 个项目具有相同的 tapGestureRecognizer (swift)

转载 作者:行者123 更新时间:2023-11-30 13:26:47 25 4
gpt4 key购买 nike

在我的应用程序中,我有一个带有个人资料图像和用户名标签的表格 View 。如果你点击2个之一那么需要做这个功能:

 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?

我怎样才能让它对他们俩都起作用?

最佳答案

您需要使用 2 个不同的 tapRecognizer,因为 UITapGestureRecognizer 只能附加到一个 View 。(“它们是附加到 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)

关于swift - 单元格中的 2 个项目具有相同的 tapGestureRecognizer (swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37088732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com