如何在列表视图中选择项目

时间:2020-12-21 13:08:35

标签: list swiftui

我在 SwiftUI 中有以下代码

struct AuthorView: View {

let authors = ["a","b","c"]
@State private var selectedAuthor = ""

var body: some View {
    VStack {
        Text("Authors").font(.title)
        HStack {
            List(authors, id: \.self, selection: $selectedAuthor) {author in
                Text(author).tag(author)
            }
            Spacer()
        }
    }
}

但由于错误“无法推断通用参数‘SelectionValue’”而无法编译。我在这里做错了什么?我的目标是获得选定的作者以供以后使用。 谢谢。

1 个答案:

答案 0 :(得分:0)

List 接口契约的选择应该是可选的,所以这里是固定部分

struct AuthorView: View {

   let authors = ["a","b","c"]
   @State private var selectedAuthor: String?      // << !!

// ... other code
}