当用户在SwiftUI中点击列表中的行时,显示包含来自行的数据的警报的最佳方法是什么?
我在用这个代码。
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()
}
}
我试着用这种方式解决这个问题:
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()
}
}
但是这个解决方案会引起这样的警告:
Attempt to present <UIAlertController:> which is already presenting <UIAlertController:>
寻找更好的解决方案或避免此警告的解决方案。
这是因为所有单元格在更新时都呈现单个变量,因此您可以尝试
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")))
}
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。