相關課程:http://hdjc8.com/hdjc/swiftUI/
Segment分段控件,類似於UIKit中的UISegmentedControl。分段控件提供一欄選項按鈕,一次只能激活其中一個選項按鈕。用於實現若干選項的單選。使用分段拾取器,可以在多個視圖區域進行快速的跳轉。
示例代碼:
struct ContentView : View {
//給當前的結構體添加一個數組屬性,作爲Picker列表的數據源。
private var animals = ["🐶 Dog", "🐯 Tiger", "🐷 Pig"]
var colors = [Color.yellow, Color.orange, Color.red, Color.purple]
//然後添加一個整型屬性,作爲列表裏的處於選擇狀態的選項的索引值,並給它添加@State綁定包裝標記,使該屬性和界面中的Picker視圖進行數據綁定。
@State private var selectedAnimal = 0
var body: some View {
VStack {
Picker(selection: $selectedAnimal, label: Text("animals")) {
ForEach(0 ..< animals.count) {
Text(self.animals[$0]).tag($0)
}
}.pickerStyle(SegmentedPickerStyle())//設置拾取器的樣式爲分段拾取器樣式。
//添加一個文本視圖,顯示用戶所選的內容。
Text("Your choice: \(animals[selectedAnimal])")
}
}
}
查看運行結果: