SwiftUI Present Alert with Input Field?

In SwiftUI I'm trying to make an alert message with input, and then get the value from the input. I've found many good tutorials how to make the Alert View in SwiftUI, but dont found how to add TextField() in Alert. This alert will update Categories table on Server, i will call a put request with this alert.

@State var isInsertAlertVisible = false
// state var is define in ContentView
// Button is define in body
Button(action: {
       self.isInsertAlertVisible = true
       }
       ,
       label: {
       Text("Create")
          .multilineTextAlignment(.center)
          .foregroundColor(Color.white)
})
.presentation($isInsertAlertVisible) {
    Alert(title: Text("Insert"), message:
        Text("Insert Categories"), dismissButton: .default(Text("OK!")){
            print("Got it")
    })

}
.padding(.all)
.background(Color.blue)

Upvotes: 0

Views: 3339

Answers (1)

Muhammad Uzair
Muhammad Uzair

Reputation: 71

struct TextfieldInAlert : View {

@State var renameFile : Bool = false

@State var newFileName : String = ""

var body: some View {

    VStack(spacing: 15) {

        Text("This is Textfield in Alert that is used to rename a file")

        Button(action: {
            renameFile = true
        }) {
            Text("Show TextField Alert")
                .background(.blue)
        }
        .buttonStyle(.plain)
    }
    .overlay() {
        ZStack {}
            .alert("Enter the new file name:", isPresented: $renameFile){
                TextField("Rename File", text: $newFileName)
                    
                Button("Rename", action: {
                    renameFile = false
                    self.PerformAction()
                })
                Button("Cancel", role: .cancel) {
                    renameFile = false
                    newFileName = ""
                }
            } message: {
                    Text("")
            }
        
    }
}
func PerformAction() {
    //Add Some Action to the Rename Button
}

}

Upvotes: 0

Related Questions