单击 swift 更新行的 属性

update a property of a row on click in swift

我有一个 table 视图,其中填充了来自 Web 服务的 json 响应。每个 table 视图行在 JSON.

中都有一个 isRead 属性

如果 isRead 为 0,我会像这样在行中添加一个蓝色小圆圈:

let myActivity = self.myActivity![indexPath.row]
if let isReadCircle = cell.viewWithTag(99874) {
    if myActivity.isRead == "0" {
       println("in isread if")
       isReadCircle.layer.cornerRadius = isReadCircle.layer.frame.height/2
       isReadCircle.backgroundColor = colorWithHexString("#3399ff")
    }
}

当我点击某行时,我想在本地更新 isRead,这样当用户按回键时,blueCircle 消失,表明该行现在已读取。

当我单击该行时,我会更新后端系统上的 isRead,但是当我按下返回键时,我不想不必要地再次调用 Web 服务。

所以我尝试的是像这样动态更新行的 属性:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if let indexPath = self.myActivityTable.indexPathForSelectedRow(){
            self.myActivity?[indexPath.row].isRead = "1"

            let cell = tableView.dequeueReusableCellWithIdentifier("ActivityCell", forIndexPath: indexPath) as! UITableViewCell
            if let isReadCircle = cell.viewWithTag(99874) {
                isReadCircle.alpha = 0
            }
        }
    }

我可以看到当我点击该行时,蓝色圆圈消失了,但是当我导航回 table 查看页面时,蓝色圆圈又回来了。新的属性如何坚持?

试试这个:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
    if let indexPath = self.myActivityTable.indexPathForSelectedRow(){
        self.myActivity?[indexPath.row].isRead = "1"

        let cell = tableView.cellForRowAtIndexPath(indexPath) as! UITableViewCell

        if let isReadCircle = cell.viewWithTag(99874) {
            isReadCircle.alpha = 0
        }

        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
        tableView.reloadData()

    }
}

更新

看来您已经直接从情节提要中设置了 segue,很不幸,方法 didSelectRowAtIndexPath 没有任何机会被解雇。在执行 segue 之前将代码从 didSelectRowAtIndexPath 移动到 prepareForSegue。可能会有帮助!