Select all text in a NSTextField using Swift

半世苍凉 提交于 2021-02-07 09:17:57

问题


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

For UITextField theres a method like

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

回答1:


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




回答2:


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
    }
}


来源:https://stackoverflow.com/questions/26126273/select-all-text-in-a-nstextfield-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!