SwiftUIでPicker を表示する
SwiftUI で Picker を表示するサンプルです。 複数行の場合はこちらです。 SwiftUIで複数行のPickerを作成する
参考: Is there a way to call a function when a SwiftUI Picker selection changes?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |