11
6

More than 3 years have passed since last update.

SwiftUI Pickerの値をenumと連動

Last updated at Posted at 2019-12-27

やりたいこと

Pickerの表示項目と選択を、モデル内のenumで管理したい

image.png image.gif

enumの値をモデル内に設定

ポイントは、enumをCaseIterableに指定すること

Model
class Model:ObservableObject{
    //enumはrawValueとしてString
    //PickerのForeachで使えるようにCaseIterableに指定
    enum Mode:String,CaseIterable{
        case a = "A"
        case b = "B"
        case c = "C"
    }
    @Published var currentMode:Mode = .a   //この値をPickerのselectionとバインド
}

Pickerにenumの値を表示し、選択と連動するように設定

Pickerのselectionで選択している項目を制御できるので、model内の値と紐付ける

ContentView
struct ContentView: View {
    //EnvironmentObjectなので、SceneDelegateに設定しておくこと
    @EnvironmentObject var model:Model

    var body: some View {
        VStack{
            Spacer()
            Text("Pickerで選択")
            //selectionでmodel内のcurrentModeとバインド 
            Picker("", selection: self.$model.currentMode) {
                //CaseIterableなenumからはallCasesでcase値を列挙できる
                ForEach(Model.Mode.allCases, id: \.self) { (mode) in
                    //rawValueの値をPickerの項目に表示
                    Text(mode.rawValue).tag(mode)
                }
            }
            .pickerStyle(SegmentedPickerStyle())
            .padding(.horizontal)
            Spacer()

            Text("選択された Mode")
            Text(self.model.currentMode.rawValue)
            .font(.largeTitle)
            Spacer()
        }
    }
}

image.gif

外部からmodeを変更した場合でも連動していることを確認

外部のボタンでmodeが変更された場合でも、Pickerの値が連動することを確認

            Text("ボタンで選択")
            HStack(spacing:40){
                ForEach(Model.Mode.allCases, id: \.self) { (mode) in
                    Button("Set:\(mode.rawValue)"){
                        //ボタンでmodeを切り替えた場合
                        self.model.currentMode = mode
                    }
                }
            }
            Spacer()

image2.gif

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6