Search code examples
swiftnstextfield

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(...)

Solution

  • 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...