0

我试图在其中显示项目,NSTableView但其中一个项目(先前由操作激活的项目(其名称存储在alreadyActivatedItem变量中))应该被禁用并以红色文本显示。

到目前为止,我设法使禁用正常工作。

我只是无法将已激活的项目着色为红色文本。我下面的代码会将所有单元格的文本涂成红色。

extension PreferencesViewController: NSTableViewDelegate {
    
    // disable selecting the already activated item
    func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
                        
        return !(myArray[row].name == alreadyActivatedItem)
    }
    
    // colouring the already activated item in red (it is also disabled)
    func tableView(_ tableView: NSTableView, willDisplayCell cell: Any, for tableColumn: NSTableColumn?, row: Int) {
        
        guard let c = cell as? NSTextFieldCell else {
            return
        }

        if c.stringValue == alreadyActivatedItem {
            c.textColor = .red
        }

    }
}

我还尝试了另一种方式:

// colouring the already activated item in red (it is also disabled)
func tableView(_ tableView: NSTableView, willDisplayCell cell: Any, for tableColumn: NSTableColumn?, row: Int) {

    guard let c = tableColumn?.dataCell(forRow: row) as? NSTextFieldCell else {
        return
    }
    
    if c.stringValue == alreadyActivatedRow {
        c.textColor = .red
    }
}

在这两种情况下,我都会有所有带有红色文本的行:

看到所有项目都是红色文本

在调试时,我可以看到:

  • let c = cell as? NSTextFieldCell似乎得到了当前行的单元格,至少我得到了stringValue正确的行c.stringValue
  • if c.stringValue == alreadyActivatedRow似乎工作得很好,至少它只有在条件为真时才会进入。

那么为什么所有的物品仍然是红色的呢?

那如何实现我的目标呢?

(Xcode 11.3.1,斯威夫特 5.1.3)

4

1 回答 1

0

细胞被重复使用。您必须添加一个else子句以始终将颜色设置为定义的状态。

if c.stringValue == alreadyActivatedItem {
    c.textColor = .red
} else {
    c.textColor = .black
}

或者更简单

 c.textColor = c.stringValue == alreadyActivatedItem ? .red : .black

我什至推荐基于视图的表格视图和 Cocoa Bindings。

于 2021-01-30T12:43:13.313 回答