My app has a tableview with an image and a textfield:
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
Example with an colored image render as default mode => default: green | selected also green | expected white, but it stay green
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.
Hope it will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With