Swift: Set Insertion Point in Nstextfield

Swift: Set Insertion Point in NSTextField

You need to set your text field current editor selected range property. Try like this:

textField.currentEditor()?.selectedRange = NSRange(location: 4, length: 0)

You will need to call displayIfNeeded

textField.displayIfNeeded()

How to find the text insertion point position in an NSTextView in Swift?


let selectedRange = self.textViewIn.selectedRanges.last
print(selectedRange ?? "No Selected")

Output: NSRange: {0, 3})

How to change insertion text (cursor) for NStextField? for os x swift 2

Never mind found the answer by extending NSTextField class and calling the function manually

extension NSTextField {
public func customizeCaretColor(caretColor: NSColor) {
let fieldEditor = self.window?.fieldEditor(true, forObject: self) as! NSTextView
fieldEditor.insertionPointColor = caretColor
}
}

NSTextField - White text on black background, but black cursor

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

NSTextField colour cursor

There's a couple ways to approach this problem.

1)

I spent some time just now writing a small sample project that customizes the cursor (which happens to be a color heart icon :-), and you can find it here.

It's based on the solutions found in this very related question.

2)

And then after doing this work, I realized that what you may simply want is to merely color an existing cursor. You can probably do that by implementing the setPointerColor:(NSColor *)newColor function found in this blog post on a NSCursor subclass that contains the cursor you want to colorize.

The important thing to remember is that you should use a subclassed NSTextField which keeps track of where the cursor is, so it can set the custom cursor or the cursor color when the mouse enters and moves around your text field.

That is, you'll need to override mouseEntered and possibly becomeFirstResponder as well, and include a tracking area to track the cursor as it crosses into your text field.

EDITED TO ADD

Turns out your question was talking about the CARET of the text field, which is the insertion point of the text and different from the mouse cursor.

Here is how you can change the color:

// change the insertion caret to another color
let fieldEditor = self.window?.fieldEditor(true, forObject: self) as! NSTextView

fieldEditor.insertionPointColor = NSColor.redColor()

The answer for which I found elaborated on here.



Related Topics



Leave a reply



Submit