如何在macOS SwfitUI中设置默认按钮?

时间:2020-02-23 04:31:07

标签: macos swiftui

我已经在SwiftUI中构建了以下模式对话框:

enter image description here

但是我不知道如何使“打开”按钮成为默认按钮(即在标准macOS HIG中以蓝色填充)。它的代码如下:

struct
OpenLocationView : View
{
    @State private var location: String = ""

    var body: some View
    {
        VStack
        {
            HStack
            {
                Text("Location:")
                TextField("https://", text: $location) { self.openLocation() }
            }

            HStack
            {
                Spacer()
                Button("Cancel") { /* dismiss window */ }
                Button("Open") { self.openLocation() }
            }
        }
        .padding()
        .frame(minWidth: 500.0)
    }

    func
    openLocation()
    {
    }
}

我尝试附加.buttonStyle(DefaultButtonStyle()),但没有明显效果。

2 个答案:

答案 0 :(得分:1)

目前在SwiftUI中无法实现,请参见此问题和解决方法SwiftUI on Mac - How do I designate a button as being the primary?

答案 1 :(得分:1)

在macOS 11上,可以使用“ keyboardShortcut”视图修饰符定义键盘快捷键。

标准键盘快捷键“ .cancelAction”(ESC键)和“ .cancelAction”(Enter键)也为关联的按钮添加了特殊的颜色。

Button("Cancel") { ... } .keyboardShortcut(.cancelAction)
Button("Open") { ... } .keyboardShortcut(.cancelAction)