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

2 items in a cell with same tapGestureRecognizer (swift)

在我的应用程序中,我有一个带有个人资料图片和用户名标签的表格视图。如果你点击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()
        }
    }

所以现在它适用于用户名标签。如果我将用户名标签放在代码的第一位,然后是 profileImg,那么它只适用于 profileImg 吗?

我怎样才能让它同时适用于他们两个?

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