Search code examples
cocoanstextfieldnstextviewnstablecellview

Change NSTextField Cursor Color When inside TableView Cell


I have an NSTextField that's inside an NSTableCelView subclass. I want to change its cursor color because right now the cursor is the same as the background.

Elsewhere in my app, I have changed the cursor color with a handy extension like this:

extension NSTextField {
  public func cursorColor(_ cursorColor: NSColor) {
    let fieldEditor = self.window?.fieldEditor(true, for: self) as! NSTextView
    fieldEditor.insertionPointColor = cursorColor
  }
}

I put this method inside viewWillDraw() in my NSTableCellView subclass:

override func viewWillDraw() {
  name.cursorColor(NSColor.white)
}

... but the app crashes on this line inside the extension:

let fieldEditor = self.window?.fieldEditor(true, for: self) as! NSTextView //Crash!

I assume it's because it can't find a reference to self.window, but I'm not sure.

Any ideas what I'm doing wrong?


Solution

  • NSWindow.fieldEditor(_: for:) returns an NSText?, yet you're trying to explicitly force-cast it to an NSTextView.

    So my guess is that either:

    1. The returned object is nil and your cast is failing or
    2. The returned object is a different subclass of NSText (and is therefore not an NSTextView) and your cast is failing

    What's the actual error message you're getting when you crash?