我试图在其中显示项目,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)