【发布时间】:2023-03-28 13:10:01
【问题描述】:
在 OSX 应用程序上,我有 3 个 NSTextField 和 2 个 NSButtons
@IBOutlet weak var TF1: NSTextField!
@IBOutlet weak var TF2: NSTextField!
@IBOutlet weak var TF3: NSTextField!
@IBOutlet weak var Bt1: NSButton!
@IBOutlet weak var Bt2: NSButton!
Bt1 将写入选定的文本字段“按下按钮 1”Bt2 将写入选定的文本字段“按下按钮 2”
但我还没有找到如何检测选择了哪个NSTextField。有人有这方面的示例代码/示例吗?
编辑:
2 个解决方案完美运行
感谢@MwcsMac 和@sfjac
@IBAction func test(_ sender: NSButton) {
var textField : NSTextField? = nil
// the focused control is the first responder of the window
let responder = sender.window?.firstResponder
// if a text field is focused, the first responder is the field editor, a NSTextView
if let textView = (responder as? NSTextView) {
if textView.isFieldEditor {
// the focused text field is the delegate of the field editor
textField = textView.delegate as? NSTextField
}
}
else {
if responder is NSTextField {
textField = responder as? NSTextField
}
}
textField?.stringValue = "test"
}
和
@IBAction func Bt1Pressed(_ sender: NSButton) {
if isTextField(inFocus: TF1){
TF1.stringValue = "B1 Pressed"
}
if isTextField(inFocus: TF2){
TF2.stringValue = "B1 Pressed"
}
if isTextField(inFocus: TF3){
TF3.stringValue = "B1 Pressed"
}
}
@IBAction func Bt2Pressed(_ sender: NSButton) {
if isTextField(inFocus: TF1) {
TF1.stringValue = "B2 Pressed"
}
if isTextField(inFocus: TF2){
TF2.stringValue = "B2 Pressed"
}
if isTextField(inFocus: TF3){
TF3.stringValue = "B2 Pressed"
}
}
func isTextField(inFocus textField: NSTextField) -> Bool {
var inFocus = false
inFocus = (textField.window?.firstResponder is NSTextView) && textField.window?.fieldEditor(false, for: nil) != nil && textField.isEqual(to: (textField.window?.firstResponder as? NSTextView)?.delegate)
return inFocus
}
【问题讨论】:
-
@Koen 我知道,但我在 Objective-C 方面真的很糟糕,所以我不明白答案
-
您不必将 Objective-C 翻译成 Swift。识别调用了哪个方法并在 Swift 中执行相同的操作。但是您的问题不是重复的,链接的问题是关于获得通知的。您要检查文本字段是否获得焦点,还是要获取焦点文本字段?
-
@Willeke 我想知道要在哪个文本字段中写入
标签: swift focus nstextfield nsbutton