Home > other >  SwiftUI Textfield Alert for macOS: Button does NOT perform action
SwiftUI Textfield Alert for macOS: Button does NOT perform action

Time:12-18

I have tried to include a TextField inside an alert in a macOS app. I have seen different sources proposing the same solution, which is actually the answer to this question - pretty simple.

However, although the TextField appears in the alert, the button does not perform any action: the code below used the exact same approved solution for the question above, I just added the print("Done") command - and it does not print. Remove the TextField, it'll print.

Is anyone experiencing the same, and maybe k now the solution to this issue?

    @State private var showingAlert = false
    @State private var input = ""

    var body: some View {
        Button("Show Alert") {
            showingAlert = true
        }
        .alert("Enter your Name", isPresented: $showingAlert) {
            TextField("Your Name", text: $input)
            Button("OK") {

                // With the TextField in the alert, this command is ignored
                print("Done")
            }
        }
    }

CodePudding user response:

I would comment but I'm not at 50 rep yet. When copying and pasting your code, the "Done" print statement does run each time upon tapping the "OK" button but a LayoutConstraint error pops up. Overall this is a weird issue you're having considering it works perfectly fine on my end. If you don't receive this error, you can disregard this but here it is:

[LayoutConstraints] Changing the translatesAutoresizingMaskIntoConstraints property
of a UICollectionViewCell that is managed by a UICollectionView is not supported,
and will result in incorrect self-sizing. View: 
<_UIAlertControllerTextFieldViewCollectionCell: 0x13df39fc0; 
frame = (0 0; 270 24); gestureRecognizers = <NSArray: 0x600001df4120>; layer = 
<CALayer: 0x6000013e13c0>>

CodePudding user response:

You should express the UI of the alert inside the alert itself like so:

var body: some View {
    Button("Show Alert") {
        self.showingAlert = true
    }
    .alert(isPresented: $showingAlert) {
        Alert(title: Text("Enter your Name"), 
              content: TextField("Your Name", text: $input), 
              dismissButton: .default(Text("OK")) {
            print("Done")
        })
    }
}

My best guess here is that because you were trying to add a button outside of the dismissButton param and inside the context of the content, its action was being ignored.

  • Related