【问题标题】:Select all text in a NSTextField using Swift使用 Swift 选择 NSTextField 中的所有文本
【发布时间】:2014-09-30 17:04:13
【问题描述】:

如何使用 Swift 以编程方式选择 NSTextField 中的所有文本?

对于 UITextField 有一个类似的方法

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

【问题讨论】:

  • 您是想从代码中的字段中获取所有文本,还是更新 NSTextField 使其看起来好像全部被选中?

标签: swift nstextfield


【解决方案1】:

在操场上试试这个:

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 键单击 selectedRange,然后单击 NSText(它的返回类型),您将跳转到其 Swiftened 标头,您可以在其中查看其丰富的功能...

【讨论】:

    【解决方案2】:

    更好的解决方案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 2015-04-23
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      相关资源
      最近更新 更多