我正在尝试制作我的文本字段(NSViewRepresentable
包裹NSTextField
) 出现时的第一个响应者。我已经测试了很多答案thread https://stackoverflow.com/questions/56507839/swiftui-how-to-make-textfield-become-first-responder,但它们要么不工作:
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*/ }
}
有人可以帮我解决这个问题吗?非常感谢!
If your MyField
is a NSTextField
以下作品。使用 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)