buttonswiftuitextfieldtvos

Text Field in Alert adds a Button


When adding a textfield to an alert in SwiftUI (as shown below) the behavior changes from tvOS 16 to tvOS 17. In the simulator running tvOS 17, it displays an additional button labeled with the text from inside the textfield when the alert is presented. So, the alert below would have two buttons. One button would be labeled "OK" and run addFunction, and the other is labeled with whatever is in $url when the alert is presented and does nothing.

Button { 
    showAlert = true
} label: {
    Image(systemName: "plus")
}
.alert("Add", isPresented: $showAlert) {
    Button("OK", action: addFunction)
    TextField("Enter URL", text: $url)
        .keyboardType(.URL)
}

I was expecting this to show an alert with one button labeled "OK". Removing the TextField removes the button, but that is not ideal and there doesn't seem to be a setting for turning the button off. Anyone else seeing this in iOS 17?


Solution

  • We can achieve buttons and textField correctly by not adding a placeholder to your textField in Alert and keeping "$name" clear. There is some bug with SwiftUI, if we add placeholder to textField or assign any value to our TextField on alert appear.

    Note: "$name" is variable that I am passing in TextField.

    Here is how to achieve textField and buttons:

    .alert("Alert Title!", isPresented: $showingAlert) {
        TextField(text: $name) {}
        Button("Submit") {
            print("Submit")
        }
        Button("Skip") {
            print("Skip")
        }
    } message: {
        Text("Enter channel name")
    }