SwiftUI Picker - 选项不会显示
SwiftUI Picker - Options won't show
我一直在尝试为应用程序实现选择器,但由于某些原因,选项不会弹出。任何帮助将不胜感激!
'''
let strengths = ["Host", "Snacks", "Drinks"]
@State private var viewModel = User.userList
var body: some View {
VStack{
Section(header: Text("Roles")) {
ForEach(User.userList) { user in
Picker(user.name, selection: $selectedStrength){
ForEach(strengths, id: \.self) { strength in
Text(strength)
}
}
// picker
}.padding()
}
}
'''
"...如何为我的所有用户创建 selectedStrength...",
你可以在你的 User
结构中添加 var strength: String
并在你的 Picker
中使用它,例如在这个示例代码中:
struct User: Identifiable {
let id = UUID()
var name: String
var strength: String // <-- here
// ...
}
struct ContentView: View {
let strengths = ["Host", "Snacks", "Drinks"]
@State private var viewModel = [User(name: "user1", strength: ""),
User(name: "user2", strength: ""),
User(name: "user3", strength: "")]
var body: some View {
NavigationView { // <-- here
Form {
Section(header: Text("Roles")) {
ForEach($viewModel) { $user in
Picker(user.name, selection: $user.strength){
ForEach(strengths, id: \.self) { strength in
Text(strength)
}
}
}.padding()
}
}
}
}
}
或者,您可以使用这个:
var body: some View {
Form {
Section(header: Text("Roles")) {
ForEach($viewModel) { $user in
HStack {
Text(user.name)
Spacer()
Picker("", selection: $user.strength){
ForEach(strengths, id: \.self) { strength in
Text(strength)
}
}.pickerStyle(.menu)
}
}.padding()
}
}
}
我一直在尝试为应用程序实现选择器,但由于某些原因,选项不会弹出。任何帮助将不胜感激!
'''
let strengths = ["Host", "Snacks", "Drinks"]
@State private var viewModel = User.userList
var body: some View {
VStack{
Section(header: Text("Roles")) {
ForEach(User.userList) { user in
Picker(user.name, selection: $selectedStrength){
ForEach(strengths, id: \.self) { strength in
Text(strength)
}
}
// picker
}.padding()
}
}
'''
"...如何为我的所有用户创建 selectedStrength...",
你可以在你的 User
结构中添加 var strength: String
并在你的 Picker
中使用它,例如在这个示例代码中:
struct User: Identifiable {
let id = UUID()
var name: String
var strength: String // <-- here
// ...
}
struct ContentView: View {
let strengths = ["Host", "Snacks", "Drinks"]
@State private var viewModel = [User(name: "user1", strength: ""),
User(name: "user2", strength: ""),
User(name: "user3", strength: "")]
var body: some View {
NavigationView { // <-- here
Form {
Section(header: Text("Roles")) {
ForEach($viewModel) { $user in
Picker(user.name, selection: $user.strength){
ForEach(strengths, id: \.self) { strength in
Text(strength)
}
}
}.padding()
}
}
}
}
}
或者,您可以使用这个:
var body: some View {
Form {
Section(header: Text("Roles")) {
ForEach($viewModel) { $user in
HStack {
Text(user.name)
Spacer()
Picker("", selection: $user.strength){
ForEach(strengths, id: \.self) { strength in
Text(strength)
}
}.pickerStyle(.menu)
}
}.padding()
}
}
}