繁体   English   中英

如何在 SwiftUI macOS 中制作第一响应者

[英]How to make first responder in SwiftUI macOS

我试图让我的 textField ( NSViewRepresentable包装的NSTextField )在它出现时成为第一响应者。 我在这个线程中测试了很多答案,但它们要么不起作用:

func updateNSView(_ nsView: MyField, context: Context) {
  if some_condition {
    print(nsViews.becomeFirstResponder()) // returns false
    negate_condition()
  }
  ...
}

或者它与日志崩溃(=== AttributeGraph: cycle detected through attribute 43 ===)

func updateNSView(_ nsViews: MyField, context: Context) {
  if some_condition {
    Window.thisWindow?.makeFirstResponder(nsViews)
    negate_condition()
  }
  ...
}

我想要实现的是:

@State var fieldActive: Bool
body: some View {
  MyField(...).onAppear { /*makeFirstResponder if fieldActive == true*/ }
}

有人可以帮我吗? 非常感谢!

如果您的MyFieldNSTextField ,则以下工作。 使用 Xcode 11.4 / macOS 10.15.4 测试

  func makeNSView(context: Context) -> MyField {
    let view = MyField()

    // ... other properties set up here

    // wait for next cycle, so field be already in window
    DispatchQueue.main.async { 
        view.window?.makeFirstResponder(view)
    }
    return view
  }

@Asperi 提供了一种有效的方法,我找到了另一种答案。 我使用SwiftUI-Introspect 库与 SwiftUI TextField(未包装的 NSTextField)一起完成工作,这里是代码:

struct SearchBar {
  @Binding var shouldActivate: Bool
  var body: some View {
    TextField("", text: text)
      .textFieldStyle(PlainTextFieldStyle())
      .introspectTextField { textField in 
          if self.shouldActivate {
              textField.becomeFirstResponder()
              self.shouldActivate = false
          }
          textField.focusRingType = .none
      }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM