NSTextField - White text on black background, but black cursor

后端 未结 9 1065
温柔的废话
温柔的废话 2020-12-14 16:23

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

相关标签:
9条回答
  • 2020-12-14 16:54

    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)
        }
    }
    
    
    0 讨论(0)
  • 2020-12-14 16:57

    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.

    0 讨论(0)
  • 2020-12-14 17:02

    I've called insertionPointColor in viewDidLoad and app crashes.

    I fixed this by calling insertionPointColor on viewDidAppear.

    For Swift developers:

    Set insertionPointColor method into extension:

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

    and call

     override func viewDidAppear() {
            super.viewDidAppear()
            textField.customizeCursorColor(NSColor.red)
        }
    
    0 讨论(0)
提交回复
热议问题