触发 UITapGesture 时从单元格的子视图中获取单元格的引用

Getting the reference of a cell from inside a childview of the cell when a UITapGesture is triggered

当从特定单元格的子视图中触发 UITapGesture 时,我正在尝试从该单元格检索数据。我当前的代码以一种我不知道它是如何计算的方式为每个单元格返回错误的单元格。有时它会因同一个单元格而改变。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "followerSeg" || segue.identifier == "followingSeg") {
        let vc = segue.destinationViewController as! FollowersFollowingVC
        let x = sender as! UITapGestureRecognizer
        let view = x.view!
        let cellone = view.superview as UIView?
        let cell = cellone?.superview as! PersonCell
        vc.userName = cell.person.profileName
        vc.userId = cell.person.id
        vc.segStatus = segue.identifier == "followerSeg" ? 0 : 1
    }
}

您可能想尝试使用 UITableView 的 indexPathForRowAtPoint 方法。我已经在 objc/iOS 工作了 5 年多,但这是我在 Swift 的第一次尝试。请原谅任何语法错误。

假设你有一个属性叫tableView,代码如下:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "followerSeg" || segue.identifier == "followingSeg") {
        let vc = segue.destinationViewController as! FollowersFollowingVC
        let x = sender as! UITapGestureRecognizer
        let location = x.locationInView(self.tableView) as CGPoint
        let indexPath = self.tableView.indexPathForRowAtPoint(location) as NSIndexPath?
        let cell = self.tableView.cellForRowAtIndexPath(indexPath!) as! PersonCell
        vc.userName = cell.person.profileName
        vc.userId = cell.person.id
        vc.segStatus = segue.identifier == "followerSeg" ? 0 : 1
    }
}