I would like to make multiple choices with the swiftui picker, is it possible?

Asked 2 years ago, Updated 2 years ago, 71 views

I am trying to use Picker to make a selection from Swiftui's Form.
Currently, it is possible to select one, for example Type 01, but would it be possible to select more than one type 01, type 02?

let TypeArray=["type01", "type02", "type03", "type04", "type05", "type06", "type07" ]
@State private var selection = 0
varbody:someView {
    US>ZStack {
        Form{
            Picker(selection:$selection, label:Text("type")){
                ForEach(0..<TypeArray.count) {numin
                    Text (self.TypeArray [num])
                }
            }
            
...abbreviated
    

swiftui form

2022-09-30 19:28

1 Answers

I don't think you can make multiple choices with Picker, so I think you need to write something close to that by yourself.
Sorry if I could select more than one.

 structure TypeEntity:Identify {
    variable —String=UUID().uuidString
    var name —String
    varisTap —Bool=false
    
    init(name:String){
        self.name = name
    }
}
structureSwiftUIView:View {
    @State private var typeSelection: Int=0
    @State private var showType:Bool=false
    @State private var TypeArray: TypeEntity = [
        TypeEntity (name: "type01"),
        TypeEntity (name: "type02"),
        TypeEntity (name: "type03"),
        TypeEntity (name: "type04"),
        TypeEntity (name: "type05"),
        TypeEntity (name: "type06"),
    ]
    var message: String {
        ifTypeArray.filter({$0.isTap}).isEmpty{
            return "Please Select"
        } else{
            var types: String = [ ]
            for type in TypeArray.filter({$0.isTap}) {
                types.append (type.name)
            }
            return types.joined(separator:",")
        }
    }
    varbody:someView {
        Form{
            HSTack {
                Text ("Type")
                Spacer()
                Button("\"(message)"){
                    self.showType.toggle()
                }
            }
            if self.showType{
                ForEach (TypeArray.indices) {in
                    HSTack {
                        ifTypeArray[i].isTap{
                            Image(systemName: "checkmark")
                        }
                        Text("\(TypeArray[i].name)")
                        Spacer()
                    }
                    .contentShape(Rectangle())
                    .onTapGesture{
                        TypeArray[i].isTap.toggle()
                    }
                }
            }
        }
    }
}

If you have a button to display the selection field like this, and if you tap the Type structure, you can set isTap to true and display a check mark in conjunction with it, you can make multiple choices.


2022-09-30 19:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.