如何选择在SwiftUI列表视图中显示的数组项?

时间:2020-04-17 07:02:22

标签: arrays list swiftui

我有一系列的自行车类型。为了查看Bike Type Picker的视图,我在SwiftUI List视图中迭代了该数组。但是,我找不到任何解决方案,如何选择/存储已窃听的列表项到State变量中。有人可以给我建议解决方案吗?

我的代码在下面:

import SwiftUI

struct BikeTypePickerView: View {
    @State var selectedBikeType: String = ""

    var bikeTypes: [String] = ["BIKE TYPE", "Benelli 125 2 C", "Benelli 125 SE", "Benelli 125 Sport", "Benelli 125 T", "Benelli 250 C", "Benelli 250 Quattro", "Benelli 250 Sport", "Benelli 254 Quattro", "Benelli 304", "Benelli 350 RS", "Benelli 354"]

    init() {
        UITableView.appearance().separatorColor = .clear
    }
    var body: some View {
        VStack {
            List(bikeTypes, id: \.self, selection: $selectedBikeType) { type in
                Text(type)
            }
        }
        .frame(width: 150, height: 400)
        .font(.system(size: 13))
        .shadow(radius: 5)
    }
}

struct BikeTypePickerView_Previews: PreviewProvider {
    static var previews: some View {
        BikeTypePickerView()
    }
}

2 个答案:

答案 0 :(得分:1)

尝试以下代码。使用下面的代码,您可以将选定的项目保存在selectedBikeType中,并在第二次点击该项目时将其删除。

struct ContentView: View {

    @State var selectedBikeType = Set<String>()

    var bikeTypes: [String] = ["BIKE TYPE", "Benelli 125 2 C", "Benelli 125 SE", "Benelli 125 Sport", "Benelli 125 T", "Benelli 250 C", "Benelli 250 Quattro", "Benelli 250 Sport", "Benelli 254 Quattro", "Benelli 304", "Benelli 350 RS", "Benelli 354"]

    init() {
        UITableView.appearance().separatorColor = .clear
    }

    var body: some View {
        VStack {
            List(self.bikeTypes, id: \.self, selection: $selectedBikeType) { type in
                Text(type)
                    .onTapGesture {
                    if self.selectedBikeType.contains(type) {
                        self.selectedBikeType.remove(type)
                    }
                    else{
                        self.selectedBikeType.insert(type)
                    }
                    print(self.selectedBikeType)
                }
            }
        }
        .frame(width: 150, height: 400)
        .font(.system(size: 13))
        .shadow(radius: 5)
    }
}

答案 1 :(得分:0)

尝试

import SwiftUI

struct BikeTypePickerView: View {
    @Binding var selectedBikeType: String

    var bikeTypes: [String] = ["BIKE TYPE", "Benelli 125 2 C", "Benelli 125 SE", "Benelli 125 Sport", "Benelli 125 T", "Benelli 250 C", "Benelli 250 Quattro", "Benelli 250 Sport", "Benelli 254 Quattro", "Benelli 304", "Benelli 350 RS", "Benelli 354"]

    init() {
        UITableView.appearance().separatorColor = .clear
    }
    var body: some View {
        VStack {
            List(bikeTypes, id: \.self, selection: $selectedBikeType) { type in
                Text(type)
            }
        }
        .frame(width: 150, height: 400)
        .font(.system(size: 13))
        .shadow(radius: 5)
    }
}