使用Swift选择NSTextField中的所有文本
问题描述:
如何使用Swift以编程方式选择NSTextField中的所有文本?使用Swift选择NSTextField中的所有文本
为UITextField那里有像
textField.selectedTextRange = textField.textRangeFromPosition(...)
答
的方法试试这个在操场:
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
Command键单击,然后NSText
(它的返回类型),它会跳到你其Swiftened标题,您可以查看其丰富的功能...
答
更好的解决方案:
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
}
}
你想获得所有从外地代码的文本,或者更新的NSTextField等等它看起来好像全部被选中了? – AlBlue 2014-09-30 22:02:00