[英]How to show an alert when the user taps on the List row in SwiftUI
What is the best way to show an alert which includes data from the row, when the user taps on the row in the List in SwiftUI?当用户在 SwiftUI 中点击列表中的行时,显示包含该行数据的警报的最佳方式是什么?
I'm using this code.我正在使用此代码。
import SwiftUI
struct ContentView: View {
var testData = ["One","Two","Three"]
var body: some View {
List{
ForEach(testData, id: \.self) { item in
Text(item).onTapGesture {
if item == "One" {
print("One selected")
print("NEED TO SHOW THE ALERT HERE")
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I tried to solve the problem this way:我试图通过这种方式解决问题:
import SwiftUI
struct ContentView: View {
@State private var showingAlert = false
var testData = ["One","Two","Three"]
var body: some View {
List{
ForEach(testData, id: \.self) { item in
Button(action: {
self.showingAlert = true
}) {
Text("\(item)")
}
.alert(isPresented: self.$showingAlert) {
Alert(title: Text("Text"), message: Text(item), dismissButton: .default(Text("Ok")))
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
But this solution causes this warning:但是这个解决方案会导致这个警告:
Attempt to present <UIAlertController:> which is already presenting <UIAlertController:>
Looking for a better solution or a solution that will avoid this warning.寻找更好的解决方案或避免此警告的解决方案。
This due to the single variable renders for all the cells when updated , so You can try这是由于更新时为所有单元格呈现单个变量,因此您可以尝试
struct ContentView: View {
@State private var showingAlert = false
@State private var item = "" // track last clicked item
var testData = ["One","Two","Three"]
var body: some View {
List{
ForEach(testData, id: \.self) { item in
Button(action: {
self.item = item
self.showingAlert = true
}) {
Text("\(item)")
}
}
}.alert(isPresented: self.$showingAlert) {
Alert(title: Text("Text"), message:Text(item), dismissButton: .default(Text("Ok")))
}
}
}
Your code creates a separate alert for each item.您的代码为每个项目创建一个单独的警报。 Move the alert
call outside the ForEach
, then only one alert instance will be created.将alert
调用ForEach
之外,那么只会创建一个警报实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.