2

I’ve built a simple macOS modal dialog in SwiftUI that takes some text from the user:

enter image description here

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)
    }
}

If the user presses enter or return, I’d like to briefly simulate a click on the default button before dismissing the dialog. How would I do this in SwiftUI?

1 Answer 1

2

Actually you've almost done it, see comments 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()
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm, you don't seem to show how to simulate the button click. What I mean by that is I want the Open button to briefly flash blue before dismissing the dialog.
@Rick see ButtonStyle protocol
@user3441734 Seems like you've got a great answer there! If you elaborate with some example code in your own answer to this question, it'll probably get accepted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.