如何获取TableView的正确索引

use*_*668 0 uitableview tableview ios swift swift3

我在TableView中有一个UILabel,并且UILabel附加到GestureRecognizer。我想做的是在标签点击时将UILabel的颜色更改为红色。现在,当我轻敲UILablel时,我非常接近,Label变为红色,但是错误的TableCell改变了颜色。如果我点击单元格3,那么我希望单元格3中的UILabel更改颜色,而不是单元格4或5。

class HomeProfilePlacesCell: NSObject {

    var CellCopy: HomeTVC?

    @objc func PostTap(_ sender: UIGestureRecognizer) {

         // This works but it often changes wrong cell
         CellCopy?.post.textColor = UIColor.red
    }

    func HomeProfilePlaceTVC(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, streamsModel : streamModel,HOMEPROFILE: HomeProfile, controller: UIViewController) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTVC", for: indexPath) as! HomeTVC
        CellCopy = cell

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(PostTap(_:)))
        tapGesture.delegate = self as? UIGestureRecognizerDelegate

        cell.post.addGestureRecognizer(tapGesture)
        cell.post.text = streamsModel.Posts[indexPath.row]
        cell.post.tag = indexPath.row

        return cell 
    }
}
Run Code Online (Sandbox Code Playgroud)

再次,代码可以正常工作,我只需要找到一种方法即可将单击的单元格的索引路径传递到PostTap方法,以便它可以更改所点击的正确单元格的颜色。任何帮助或建议都会很棒。我不想使用“表刷新”,因为我仅在单击的单元格中更改了1个UILabel。

Roc*_*cky 5

不需要获取标签为Taped的单元格的索引。UIGestureRecognizer有一个UIView手势连接到,所以要更改标签颜色只是做在你的PostTap方法:

sender.view?.backgroundColor = .red
Run Code Online (Sandbox Code Playgroud)