tableview图像内容选择颜色

Gho*_*108 18 macos cocoa colors tableview swift

我的应用程序有一个带有图像和文本字段的tableview:

  • image =图像渲染为模板图像(浅灰色)
  • textfield =文字颜色黑色

如果我选择一行,两者的颜色将完全变为白色

问题 - 我将图像更改为蓝色图像=渲染为默认值.如果我现在选择一行,我的文本字段的文本颜色将变为白色,但图像将保持蓝色.

我希望图像也将颜色改为白色,但事实并非如此.

我做错了什么?

将图像渲染为模板模式的示例=> default:gray | 自动选择白色

在此输入图像描述

彩色图像的示例呈现为默认模式=>默认值:绿色| 也选择了绿色| 预计白色,但它保持绿色

在此输入图像描述

Yuy*_*tsu 2

尝试这个:

    import Cocoa

class ViewController: NSViewController {
    @IBOutlet weak var tableView:NSTableView!
    var selectIndex = -1
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self
        self.tableView.dataSource = self

    }

    func tintedImage(_ image: NSImage, tint: NSColor) -> NSImage {
        guard let tinted = image.copy() as? NSImage else { return image }
        tinted.lockFocus()
        tint.set()

        let imageRect = NSRect(origin: NSZeroPoint, size: image.size)
        NSRectFillUsingOperation(imageRect, .sourceAtop)

        tinted.unlockFocus()
        return tinted
    }
}

extension ViewController:NSTableViewDataSource, NSTableViewDelegate{
    func numberOfRows(in tableView: NSTableView) -> Int {
        return 3
    }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView?{


        let result = tableView.make(withIdentifier: "imageIcon", owner: self) as! NSTableCellView
        if selectIndex == row{
            result.imageView?.image = self.tintedImage(NSImage(named:"file")!, tint: NSColor.green)

        }else{
            result.imageView?.image = self.tintedImage(NSImage(named:"file")!, tint: NSColor.gray)

        }
        return result

    }

    func tableView(_ tableView: NSTableView, didAdd rowView: NSTableRowView, forRow row: Int) {
        if selectIndex == row{
            rowView.backgroundColor = NSColor.blue
        }else{
            rowView.backgroundColor = NSColor.clear
        }
    }


    func tableViewSelectionDidChange(_ notification: Notification) {
        let table = notification.object as! NSTableView
        self.selectIndex = tableView.selectedRow

        print(table.selectedRow);
        table.reloadData()
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:根据您的要求更改 imageView TintColor 颜色。

带颜色的表格行选择
希望它能帮助你。