应用程序启动后,在Swiftui的Textfield上禁用自动对焦

发布于 2025-01-25 18:22:26 字数 445 浏览 3 评论 0原文

MacOS 12将Textfield设置为发射时的第一响应者几秒钟,然后再进行更改。

尝试调用下面的方法,diDishlaunching,willfinishlaunching,init()主应用程序的init(),

       NSApp.keyWindow?.makeFirstResponder(nil)
       NSApp.keyWindow?.resignFirstResponder()

在该应用程序自动删除焦点之前,短暂延迟了几秒钟。

如何防止这种行为?我有一些动画,当Textfield集中时会触发。

 enum Focus { case some, none }

 @FocusState var focus : Focus

正在观察到,启动焦点设置为某些,然后将其设置为无

macOS 12 sets the TextField as first responder on launch for a few seconds before this changes.

Tried calling the methods below onAppear, didFinishLaunching, willFinishLaunching, init() of the main app

       NSApp.keyWindow?.makeFirstResponder(nil)
       NSApp.keyWindow?.resignFirstResponder()

There is a brief delay of a few seconds before the app automatically removes focus.

How to prevent this behaviour ? I have some animations which are triggered when the TextField is focused.

I'm using

 enum Focus { case some, none }

 @FocusState var focus : Focus

I've observed that on launch focus is set to some and then to nil

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瑶笙 2025-02-01 18:22:26

这确实看起来像一个错误(如果需要,请向Apple提出反馈)。

发现的解决方法是禁用启动的临时控制(禁用> Textfield 无法获得焦点)并在下一个事件周期中重新确定。

用Xcode 13.3/MacOS测试12.2

这是主要部分:

TextField("", text: $txt)
    .disabled(disabled)     // << here !!
    .onAppear { 
       DispatchQueue.main.async { disabled = false } // << here !!
    }

项目中的完整代码在这里

This really looks like a bug (file a feedback to Apple if you want).

A found workaround is to disable temporary control on launch (disabled TextField cannot get focus) and reenable it in next event cycle.

Tested with Xcode 13.3 / macOS 12.2

Here is main part:

TextField("", text: $txt)
    .disabled(disabled)     // << here !!
    .onAppear { 
       DispatchQueue.main.async { disabled = false } // << here !!
    }

Complete code in project is here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文