显示SwiftUi Alert功能中的TextField



我是SwiftUi的新手,我试图用TextField和动作按钮显示警报消息,我想为此使用警报功能,但我不能在警报功能中添加TextField,我在下面共享代码,我如何在警报功能中添加TextField ?谢谢. .

.alert(isPresented:$showAlertDialog) {                                            
Alert(
title: Text("Please Enter sended E-mail Code"),
message: Text("There is no undo"),
primaryButton: .destructive(Text("Submit")) {
print("Deleting...")
},
secondaryButton: .cancel()
)
}

从iOS 15开始,警报无法显示TextField。但是你可以自定义SwiftUI警报。

struct TextFieldAlert: ViewModifier {
@Binding var isPresented: Bool
let title: String
@Binding var text: String
let placeholder: String
let action: (String) -> Void
func body(content: Content) -> some View {
ZStack(alignment: .center) {
content
.disabled(isPresented)
if isPresented {
VStack {
Text(title).font(.headline).padding()
TextField(placeholder, text: $text).textFieldStyle(.roundedBorder).padding()
Divider()
HStack{
Spacer()
Button(role: .cancel) {
withAnimation {
isPresented.toggle()
}
} label: {
Text("Cancel")
}
Spacer()
Divider()
Spacer()
Button() {
action(text)
withAnimation {
isPresented.toggle()
}
} label: {
Text("Done")
}
Spacer()
}
}
.background(.background)
.frame(width: 300, height: 200)
.cornerRadius(20)
.overlay {
RoundedRectangle(cornerRadius: 20)
.stroke(.quaternary, lineWidth: 1)
}
}
}
}
}
extension View {
public func textFieldAlert(
isPresented: Binding<Bool>,
title: String,
text: Binding<String>,
placeholder: String = "",
action: @escaping (String) -> Void
) -> some View {
self.modifier(TextFieldAlert(isPresented: isPresented, title: title, text: text, placeholder: placeholder, action: action))
}
}

在根视图中使用。(例如,不要将其连接到Buttons或其他内部元素)。这将确保显示视图被禁用。示例用法:

struct ContentView: View {
@State var isAlertDisplayed = false
@State var text = "Text to change"

var body: some View {
VStack {
Text("Press the button to show the alert").multilineTextAlignment(.center)
Text("Current value is: (text)")
Button("Change value") {
withAnimation {
isAlertDisplayed = true
}
}
.padding()
}
.textFieldAlert(isPresented: $isAlertDisplayed, title: "Some title", text: $text, placeholder: "Placeholder", action: { text in
print(text)
})
.padding()
}
}

我认为你实际上可以-也许它在iOS 16中回来了。这对我来说是有效的:

.alert("Alert message...", isPresented: $isShowingAlert) {
TextField("", text: $alertInput)
Button("OK", action: {})
}

最新更新