SwiftUIでPicker を表示する


SwiftUI で Picker を表示するサンプルです。 複数行の場合はこちらです。 SwiftUIで複数行のPickerを作成する

Picker Sample

参考: Is there a way to call a function when a SwiftUI Picker selection changes?

import SwiftUI
struct ContentView: View {
var pokemons = ["Snorlax", "Pikachu", "Slowpoke", "Meowth"]
@State private var selectedPokemon = 0
var body: some View {
Picker("Pokemon", selection: $selectedPokemon) {
ForEach(0 ..< pokemons.count) {
Text(self.pokemons[$0])
}
}.pickerStyle(WheelPickerStyle())
.onReceive([self.selectedPokemon].publisher.first()) { (value) in
print("selectedPokemon: \(value)")
print(self.pokemons[value])
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}