【问题标题】:Simulate button click in macOS SwiftUI?在 macOS SwiftUI 中模拟按钮点击?
【发布时间】:2020-06-07 02:39:58
【问题描述】:

我在 SwiftUI 中构建了一个简单的 macOS 模式对话框,它从用户那里获取一些文本:

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") { self.dismiss() }
                Button("Open") { self.simulateClick() }
            }
        }
        .padding()
        .frame(minWidth: 500.0)
    }
}

如果用户按下回车键或回车键,我想在关闭对话框之前简要模拟点击默认按钮。我将如何在 SwiftUI 中执行此操作?

【问题讨论】:

    标签: macos button swiftui


    【解决方案1】:

    其实你已经差不多完成了,见 cmets inline

    ...
        HStack
        {
            Text("Location:")
            TextField("https://", text: $location) { 
               // this is onCommit: called on Return or Enter
               self.open() 
            }
        }
    
        HStack
        {
            Spacer()
            Button("Cancel") { self.dismiss() }
            Button("Open") { self.open() }
        }
    
    ...
    
    func open() {
        self.openLocation() 
        self.dismiss()
    }
    

    【讨论】:

    • 嗯,你似乎没有展示如何模拟按钮点击。我的意思是我希望打开按钮在关闭对话框之前短暂闪烁蓝色。
    • @Rick 查看 ButtonStyle 协议
    • @user3441734 好像你有一个很好的答案!如果您在自己对这个问题的回答中详细说明了一些示例代码,它可能会被接受!
    猜你喜欢
    • 2022-01-03
    • 2015-06-28
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    相关资源
    最近更新 更多