如何在SwiftUI macOS中制作第一响应者 [英] How to make first responder in SwiftUI macOS

查看:166
本文介绍了如何在SwiftUI macOS中制作第一响应者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使我的textField(用NSTextField包装的NSTextField)成为第一个响应者.我已经在线程中测试了很多答案,但是它们是要么不起作用:

I'm trying to make my textField (NSViewRepresentable wrapped NSTextField) the first responder when it appears. I have tested many answers in this thread, but they are either not working:

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

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

Can someone please help me on this? Thank you very much!

推荐答案

如果您的MyFieldNSTextField,则可以使用以下方法.使用Xcode 11.4/macOS 10.15.4进行了测试

If your MyField is a NSTextField the following works. Tested with 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
  }

这篇关于如何在SwiftUI macOS中制作第一响应者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆