ixany
ixany

Reputation: 6040

Select all text in a NSTextField using Swift

How can I programatically select all the text in a NSTextField using Swift?

For UITextField theres a method like

textField.selectedTextRange = textField.textRangeFromPosition(...)

Upvotes: 4

Views: 4462

Answers (2)

Konstantin Cherkasov
Konstantin Cherkasov

Reputation: 3343

Better solution:

import Cocoa

class TextFieldSubclass: NSTextField {
    override func mouseDown(theEvent: NSEvent) {
        super.mouseDown(theEvent)
        if let textEditor = currentEditor() {
            textEditor.selectAll(self)
        }
    }
}

Or for precise selection:

import Cocoa

class TextFieldSubclass: NSTextField {
    override func mouseDown(theEvent: NSEvent) {
        super.mouseDown(theEvent)
        if let textEditor = currentEditor() {
            textEditor.selectedRange = NSMakeRange(location, length)
        }
    }
}

Works for me:

import Cocoa

class TextFieldSubclass: NSTextField {
    override func becomeFirstResponder() -> Bool {
        let source = CGEventSourceCreate(CGEventSourceStateID.HIDSystemState)
        let tapLocation = CGEventTapLocation.CGHIDEventTap
        let cmdA = CGEventCreateKeyboardEvent(source, 0x00, true)
        CGEventSetFlags(cmdA, CGEventFlags.MaskCommand)
        CGEventPost(tapLocation, cmdA)
        return true
    }
}

Upvotes: 3

Milos
Milos

Reputation: 2758

Try this in a playground:

import XCPlayground
import AppKit

let view = NSView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))

XCPShowView("view", view)

let txtf = NSTextField(frame: CGRect(x: 50, y: 50, width: 200, height: 50))

view.addSubview(txtf)

txtf.stringValue = "falling asleep at the keyboard..."

txtf.selectText(nil) // Ends editing and selects the entire contents of the text field

var txt = txtf.currentEditor() // returns an NSText

txt.selectedRange // --> (0,33)

Command-click on selectedRange, then on NSText (its return type), which will jump you to its Swiftened header where you can check out its rich functionality...

Upvotes: 5

Related Questions