NSTextField - White text on black background, but black cursor

Viewed 12041

I've setup an NSTextField with text color as white, and the background color as (black despite not rendering the background color, so its transparent). All in Interface Builder.

The problem I am having is the cursor is black, and hardly visible. Does the cursor not represent the text color? Any ideas how I can fix this?

Otherwise, the NSTextField looks like it cannot be edited.

10 Answers

Your best bet is probably to use NSTextView and - (void)setInsertionPointColor:(NSColor *)color.

Assuming that you are wanting to set the color of the insertion caret and not the mouse cursor then the suggestion of using setInsertionPointColor: should work.

However, you do not necessarily need to change from using NSTextField to NSTextView. The field editor for window that the NSTextField is in is an NSTextView. So when your NSTextField becomes the key view you could grab the field editor and call setInsertionPointColor: on that. You may need to reset the color when your field stops being the key view.

You can get the field editor by using NSWindow's fieldEditor:forObject: or NSCell's fieldEditorForView:.

If you have a subclass of NSTextField you can have it use a custom subclass of NSTextFieldCell and override -(NSText*)setUpFieldEditorAttributes:(NSText*)textObj. In that method you can set the insertion point color once and it will stay while the field editor is active for this text field. Though when the field editor is moved to another edit field the insertion point color will remain unless you reset it.

Swift 4 Solution

override func viewDidAppear() {
    super.viewDidAppear()
    guard let window = _textField.window, let fieldEditor = window.fieldEditor(true, for: _textField) as? NSTextView else { return }
    fieldEditor.insertionPointColor = .white
}

easiest way is

 override func viewDidAppear() {
    if let fieldEditor = self.view.window?.fieldEditor(true, for: self) as? NSTextView{
        fieldEditor.insertionPointColor = NSColor.black
    }
 }

I use this code in swift

 if let editor = textField.currentEditor() as? NSTextView{
     editor.insertionPointColor = myColor ?? .black
 }

If you use Objective-C runtime selector capture combined with uliwitness's solution, you can achieve it without subclassing NSTextField, here I use RxCocoa's methodInvoked as an example:

import Cocoa
import RxCocoa

extension NSTextField {
    func withCursorColor(_ color: NSColor) {
        rx.methodInvoked(#selector(becomeFirstResponder))
            .subscribe(onNext: { [unowned self] _ in
                guard let editor = self.currentEditor() as? NSTextView else { return }
                editor.insertionPointColor = color
            })
            .disposed(by: rx.disposeBag)
    }
}

Related