Anyone an idea how to create an Alert in SwiftUI that contains a TextField?
This is an example based on the SwiftUI Sheet
class that displays a dialog with a prompt, a text field, and the classic OK and Dismiss button
First lets make our Dialog
class, which will pop when user want to edit a value:
import SwiftUI
struct Dialog: View {
@Environment(\.presentationMode) var presentationMode
/// Edited value, passed from outside
@Binding var value: String?
/// Prompt message
var prompt: String = ""
/// The value currently edited
@State var fieldValue: String
/// Init the Dialog view
/// Passed @binding value is duplicated to @state value while editing
init(prompt: String, value: Binding) {
_value = value
self.prompt = prompt
_fieldValue = State(initialValue: value.wrappedValue ?? "")
}
var body: some View {
VStack {
Text(prompt).padding()
TextField("", text: $fieldValue)
.frame(width: 200, alignment: .center)
HStack {
Button("OK") {
self.value = fieldValue
self.presentationMode.wrappedValue.dismiss()
}
Button("Dismiss") {
self.presentationMode.wrappedValue.dismiss()
}
}.padding()
}
.padding()
}
}
#if DEBUG
struct Dialog_Previews: PreviewProvider {
static var previews: some View {
var name = "John Doe"
Dialog(prompt: "Name", value: Binding.init(get: { name }, set: {name = $0 ?? ""}))
}
}
#endif
Now we use it this way in the caller View:
import SwiftUI
struct ContentView: View {
/// Is the input dialog displayed
@State var dialogDisplayed = false
/// The name to edit
@State var name: String? = nil
var body: some View {
VStack {
Text(name ?? "Unnamed").frame(width: 200).padding()
Button(name == nil ? "Set Name" : "Change Name") {
dialogDisplayed = true
}
.sheet(isPresented: $dialogDisplayed) {
Dialog(prompt: name == nil ? "Enter a name" : "Enter a new name", value: $name)
}
.onChange(of: name, perform: { value in
print("Name Changed : \(value)")
}
.padding()
}
.padding()
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif