Friday, August 2, 2024
HomeiOS Developmentios - Doable to have the enter / return key activate the...

ios – Doable to have the enter / return key activate the “OK” button on a SwiftUI Alert with a textfield?


I’ve an Alert in my SwiftUI app:

.alert("Mission Identify:", isPresented: self.$alertPresented)
{
    TextField("", textual content: self.$userInput)
    /*.onSubmit
    {
        okButtonPushed()
        self.alertPresented = false
    }*/
    Button("Cancel", position: .cancel) { }
    Button("OK")
    {
        okButtonPushed()
    }
    .disabled(userInput.isEmpty)//.keyboardShortcut(.return)
}

It really works fantastic as regular, however what I am attempting to do is make it so when the consumer hits the return or enter key on MacOS, it will likely be the identical as if the consumer clicked the OK Button. I additionally need the OK Button to be highlighted in order that it is clear to the consumer that they’ll hit return / enter to activate it.

I’ve tried two totally different approaches up to now. The primary, I’ve connected an .onSubmit to the TextField. After I hit enter or return, it really works however it does not dismiss the Alert (even when I set $self.alertPresented to false.

The second, I’ve tried attaching a .keyboardShortcut(.return) to the OK Button itself however all this does is spotlight the cancel Button for some cause (a lot in the identical method I wish to spotlight the OK Button), and once I hit return / or enter, the Alert disappears like somebody clicked the cancel Button.

So, simply questioning if that is attainable within the format I’ve above, the place the Alert has a TextField and when it is all carried out in an .alert enclosure connected to a Button. Thanks.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments