LoginSignup
1
2

More than 3 years have passed since last update.

【SwiftUI】Picker使ってみた

Last updated at Posted at 2021-05-15

今回作成するアプリに複数の選択肢から1つだけ値を選択する機能が必要なので
Pickerという部品を使って実装してみました。

SwiftUI初学者の方々に参考になれば嬉しいです。

実装後の動作は以下になります。

mojikyo45_640-2.gif

ソースコードは以下です。

import SwiftUI

struct ContentView: View {
    @State var selection: String = "和食"
    var array: [String] = ["和食", "洋食", "中華"]

    var body: some View {
        VStack {
            Picker(selection: $selection,label: Text(selection).frame(width: 100))  {
                ForEach(array, id: \.self) { word in
                    Text(word).tag(word)
                }
            }
            .pickerStyle(MenuPickerStyle())
            .padding()
            .cornerRadius(5)
            Text("選択値:\(selection)")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

pickerStyleを変更すれば、よくあるスクロール形式?のリスト表示も出来ます。

ここをこうした方が可読性が上がるとか、もっとスマートになるとかあればコメントお願いします。
※見直したらGIFの動きがめちゃくちゃ遅いですね。変換時の設定ミスっぽいです。気をつけます

1
2
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
1
2