You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI带TextField的Alert如何让回车触发OK按钮并高亮该按钮?

macOS SwiftUI Alert 回车触发OK按钮并高亮解决方案

针对你遇到的问题,直接调整按钮的键盘快捷键设置并补充Alert关闭逻辑即可实现需求,修改后的代码如下:

.alert("Project Name:", isPresented: self.$alertPresented) {
    TextField("", text: self.$userInput)
        .onSubmit {
            okButtonPushed()
            self.alertPresented = false
        }
    Button("Cancel", role: .cancel) {}
    Button("OK") {
        okButtonPushed()
        self.alertPresented = false
    }
    .disabled(userInput.isEmpty)
    .keyboardShortcut(.defaultAction)
}

关键调整说明:

  • 给OK按钮使用.keyboardShortcut(.defaultAction):这是macOS SwiftUI中设置Alert默认操作按钮的标准方式,系统会自动高亮该按钮,按下回车键时直接触发它,不会出现Cancel按钮抢占回车响应的问题。
  • 补充self.alertPresented = false:无论点击OK按钮还是在TextField中按回车,都手动关闭Alert,解决之前仅触发逻辑但Alert不关闭的问题。
  • 保留Cancel按钮的.cancel角色:确保它依然拥有ESC键触发的系统默认行为,同时不影响回车对OK按钮的绑定。

内容的提问来源于stack exchange,提问作者Ser Pounce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:13:14