IOS Swift如何使用TableView回收突出显示一个单元格

时间:2016-12-14 18:46:59

标签: ios swift uitableview swift3

我有一个TableView和一个名为Post的标签。我有一个Gesture Tap功能,当用户点击该标签时,被点击的TableView标签会改变颜色。问题是使用tableView回收,如果我沿着tableView向下看,那么其他单元格也会突出显示未被单击。如何修复它以便仅突出显示单击的单元格?这是我的代码

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserProfileTVC", for: indexPath) as! UserProfileTVC

        cell.post.text = Posts[indexPath.row]
        let post_tap = UITapGestureRecognizer(target: self, action: #selector(UserProfileC.post_tapped(sender:)))
        cell.post.addGestureRecognizer(post_tap)
        return cell
    }


    func post_tapped(sender:UITapGestureRecognizer) {

        let point = CGPoint(x: 0, y: 0)

        let position: CGPoint = sender.view!.convert(point, to: self.TableSource)
        if self.TableSource.indexPathForRow(at: position) != nil {
            sender.view?.backgroundColor = UIColor.blue

        }
    }

代码再次起作用并突出显示正确的TableCell标签,当向下滚动tableView时,问题是其他tableCells标签也会在不单击的情况下突出显示。

我已使用下面给出的示例更新了代码,但它仍然给出了相同的结果

if let existingRecognizerView = cell.viewWithTag(101) as UIView?  {

        existingRecognizerView.backgroundColor = UIColor.white


    } else {

let post_tap = UITapGestureRecognizer(target: self, action: #selector(UserProfileC.post_tapped(sender:)))
        post_tap.view?.tag = 101

    cell.post.addGestureRecognizer(post_tap)

    }

1 个答案:

答案 0 :(得分:1)

cellForRowAtIndexPath函数中,您正在使用蓝色背景将已有UITapGestureRecognizer的单元格出列。您需要在其视图中添加一个标记,以便在出列并删除背景颜色时可以访问它。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "UserProfileTVC", for: indexPath) as! UserProfileTVC

    cell.post.text = Posts[indexPath.row]

    // Check if we already have a GestureRecognizer view
    if let existingRecognizerView = cell.post.viewWithTag(101) {
        existingRecognizerView.backgroundColor = UIColor.white
    } else {
        let post_tap = UITapGestureRecognizer(target: self, action: #selector(UserProfileC.post_tapped(sender:)))
        cell.post.addGestureRecognizer(post_tap)
        post_tap.view.tag = 101
    }

    return cell
}


func post_tapped(sender:UITapGestureRecognizer) {

    let point = CGPoint(x: 0, y: 0)

    let position: CGPoint = sender.view!.convert(point, to: self.TableSource)
    if self.TableSource.indexPathForRow(at: position) != nil {
        sender.view?.backgroundColor = UIColor.blue

    }
}

*注意:从移动设备编码......未针对语法或功能错误进行测试。