在 SwiftUI 中,我尝试使用输入发出警报消息,然后从输入中获取值。我发现了很多关于如何在 SwiftUI 中制作 Alert View 的好教程,但没有找到如何在 Alert 中添加 TextField() 。此警报将更新服务器上的类别表,我将使用此警报调用 put 请求。
@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)
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
}
}