如何获取列表中选定行的值?

例如:

var data: [String] = []    

List {
   ForEach(0..<data.count, id: \.self) { item in
     HStack {
        Text(data[item])
     }
   }
} //: End of the List

.onDelete(perform: { indexSet in
   // get the value of the row
   // get the corresponding key for the value
   // delete the value by the key from the dictionary
}) //: End of the onDelete

.onAppear {
   let dictionary = //retrieve the data from the database and get a dictionary
   for entry in dictionary {
      data.append(entry.value)
   }
} //: End of the onAppear

如何获取列表中选定行的值?

推荐答案

如果必须获取已删除元素的值,则可以这样try .代码在图像下方.

如果只需要选定元素的值,则只需使用$selection即可.

enter image description here

struct DemoView: View {
@State var list = ["dog", "cat", "turtle"]
@State var atIndex = 0
@State var temp = ""
var body: some View {
    List(selection: $temp) {
        ForEach(list, id: \.self) { sub in
            HStack {
                Text(sub)
            }
        }
        .onDelete { indexSet in
            indexSet.forEach { i in
                atIndex += i
            }
            temp = list[atIndex]
            print("I am going to delete \(temp)")
            list.remove(atOffsets: indexSet)
            atIndex = 0
        }
        Text("Recent deleted value: \(temp)")
    }
  }
}

Swift相关问答推荐

如何让ScrollView缩小到合适的大小,并在没有黑客攻击的情况下占用最小空间

在按下按钮动画后执行按钮动作

如何才能在同一线程上调用类中的每个方法,而不对每个调用使用同步块?

如何避免切换视图递归onChange调用SwiftUI

如何使用可搜索在搜索栏中搜索包括>或<?

SwiftUI 交易:根据外部状态制作一个动画或静止的按钮

列表不显示信息

使第二个视图变灰 SwiftUI

Firebase removeObserver 在 Swift 5 中不起作用

Swiftui 按钮依次显示一组图像

SwiftUI - Select 器没有 Select 值

令人满意的 var body:协议扩展中的一些视图

使用 Swiftui 水平修剪 Shape()

如何使用 Date.ParseStrategy 在 Swift 5.6 中将字符串解析为日期?

iOS 判断应用程序是否可以访问麦克风

Xcode 6 中的嵌入式内容包含 Swift 代码构建设置有什么作用?

在 Xcode 中自动实现 Swift 协议方法

Swift 的 JSONDecoder 在 JSON 字符串中有多种日期格式?

TabView 在切换选项卡时重置导航堆栈

更改在变量的 willSet 块中设置的值