如何使用Swift以编程方式选择NSTextField中的所有文本?
对于UITextField,有一个类似
的方法textField.selectedTextRange = textField.textRangeFromPosition(...)
答案 0 :(得分:4)
在操场上试试这个:
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)
按住selectedRange
,然后点击NSText
(其返回类型),这会跳转到其Swiftened标题,您可以在其中查看其丰富的功能...
答案 1 :(得分:1)
更好的解决方案:
import Cocoa
class TextFieldSubclass: NSTextField {
override func mouseDown(theEvent: NSEvent) {
super.mouseDown(theEvent)
if let textEditor = currentEditor() {
textEditor.selectAll(self)
}
}
}
或者是为了精确选择:
import Cocoa
class TextFieldSubclass: NSTextField {
override func mouseDown(theEvent: NSEvent) {
super.mouseDown(theEvent)
if let textEditor = currentEditor() {
textEditor.selectedRange = NSMakeRange(location, length)
}
}
}
适合我:
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
}
}