Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tableview image content selection color

My app has a tableview with an image and a textfield:

  • image = image render as template image (light grey)
  • textfield = text color black

If I select a row, the color of both will change perfectly to white

Question - I change the image to a blue color image = render as default. If I now select a row, the text color of my textfield will change to white, but the image will stay blue.

I want the image change the color to white too but it doesn't.

What did I do wrong?

Example with an image render as template mode => default: grey | selected automatically white

enter image description here

Example with an colored image render as default mode => default: green | selected also green | expected white, but it stay green

enter image description here

like image 400
Ghost108 Avatar asked Aug 28 '17 15:08

Ghost108


1 Answers

Try this:

    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()
    }
}

Note: Change imageView tintColor color as per your requirement.

table row selection with color
Hope it will help you.

like image 156
Yuyutsu Avatar answered Sep 24 '22 16:09

Yuyutsu