我正在嘗試開發一個Picker與標題相對應的欄位。問題是我不明白如何使用Picker視圖的標題欄位。
這是代碼。問題是Picker以string "Spain". "Select country"相反,我想要在用戶選擇一個欄位之前可見的標題。


struct CustomPicker: View {
@State private var selection = "Select country"
let colors = ["Spain", "France"]
var body: some View {
VStack(alignment: .leading, spacing: 4, content: {
HStack(spacing: 15) {
Picker("Select country", selection: $selection) {
ForEach(colors, id: \.self) {
Text($0)
}
}
.pickerStyle(DefaultPickerStyle())
}
.padding(.horizontal, 20)
})
.frame(height: 50)
.background(.white)
.cornerRadius(10)
.padding(.horizontal, 20)
}
}
uj5u.com熱心網友回復:
您嘗試做的事情并不符合 SwiftUI 的標準。您必須為此定制您的 UI(這可能并不難)。根據您愿意妥協的程度,您可以通過稍微調整代碼來獲得您想要的東西。這是串列中選擇器的樣子(以及串列中的選擇器)。
為此,我稍微修改了您的代碼以包含國家/地區的列舉。
enum Country: String, CaseIterable, Identifiable {
case spain, france, germany, switzerland
var id: Self { self }
}
struct CustomPicker: View {
@State private var selection: Country = .spain
var body: some View {
NavigationView {
List {
Picker("Select Country", selection: $selection) {
ForEach(Country.allCases, id: \.self) {
Text($0.rawValue.capitalized)
.tag($0)
}
}
Picker("Select Country", selection: $selection) {
ForEach(Country.allCases, id: \.self) {
Text($0.rawValue.capitalized)
.tag($0)
}
}
.pickerStyle(.menu)
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle("Country Picker")
}
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468553.html
