Why does this SwiftUI Picker code not work?
ForEach types inside Picker should be aligned with selection type.
Here is a corrected code that should work for you:
@State private var letter = ""
private let letters = ["Alpha", "Bravo", "Charlie"]
var body: some View {
NavigationView {
Form {
Picker("Select a letter", selection: $letter) {
ForEach(letters, id: \.self) { option in
Text(option)
}
}
Text("Selected letter: \(letter)")
}
.navigationBarTitle("Main Menu")
}
}
Why does binding to the Picker not work anymore in swiftui?
I found a way to simplify the code a bit without the need of operating on indicies and tags.
At first, make sure to conform your model to Identifiable
protocol like this (this is actually a key part, as it enables SwiftUI to differentiate elements):
public enum EditScheduleMode: String, CaseIterable, Identifiable {
case closeSchedule
case openSchedule
public var id: EditScheduleMode { self }
var localizedTitle: String { ... }
}
Then you can declare viewModel like this:
public class EditScheduleViewModel: ObservableObject {
@Published public var editScheduleMode = EditScheduleMode.closeSchedule
public let modes = EditScheduleMode.allCases
}
and UI:
struct ModeSelectionView: View {
private let elements: [EditScheduleMode]
@Binding private var selectedElement: EditScheduleMode
internal init?(elements: [EditScheduleMode],
selectedElement: Binding<EditScheduleMode>) {
self.elements = elements
_selectedElement = selectedElement
}
internal var body: some View {
VStack {
Picker("", selection: $selectedElement) {
ForEach(elements) { element in
Text(element.localizedTitle)
}
}
.pickerStyle(.segmented)
}
}
}
With all of those you can create a view like this:
ModeSelectionView(elements: viewModel.modes, selectedElement: $viewModel.editScheduleMode)
SwiftUI: Why doesn't picker display?
Likely an older video, if you set the pickerStyle
to .wheel
Picker("How do you want to pay?", selection: $paymentType) {
//Your code
}.pickerStyle(.wheel)
you will get that look. Right now it is likely a menu style. When you don't set the type Apple can pick which style to use.
SwiftUI Picker not displaying Options
I recently managed to resolve this problem.
Picker needs to be wrapped in a NavigationView before it will work in a form.
I was able to simply add a NavigationView to the top of my view and put the form inside it, and now the picker works perfectly.
var body: some View{
NavigationView{
Form{
....
Picker()
....
}
}
}
SwiftUI picker in Form not working properly
This happens with optionals quite a bit you just have to specify type
Change your tags to something like this
.tag(month as? Month)
.tag(category as? Category)
The types have to match exactly. month
and category
are non-optionals so they need to be cast to optionals since your @State
is an optional
iOS 15 SwiftUI 3 Picker binding is not working after changing @State value
Seems like iOS 15 does not work like before to change the value of State
var and send it as Binding to a Picker.
the issue is that the State var selectedCategory
is sent to the Picker as Binding and when I try to change the value of selectedCategory
var on appearing the view, the binding is not being updated and the Picker value does not change when you select a different category.
What I did is to change the selectedCategory
value in the init
function before initializing the Picker:
import SwiftUI
struct Category: Identifiable {
let id: UUID = UUID()
let name: String
}
let categories: [Category] = [
Category(name: "Cat 1"),
Category(name: "Cat 2"),
Category(name: "Cat 3")
]
struct ContentView: View {
@State private var selectedCategory = -1
init() {
self._selectedCategory = State(initialValue: 1)
}
var body: some View {
NavigationView {
Form {
Section {
Picker("Category", selection: $selectedCategory) {
ForEach(0..<categories.count) {
Text(categories[$0].name)
.tag($0)
}
}
}
}
}
}
}
Why do I need to assign a value on the init?
this is because in my project I need to update a Core Data record and I send the record to the view as ObservedObject
and to change the category I need to change selectedCategory
to have the value of the Core Data record and not the default value, by changing the value in onAppear
the Picker get broken and does not work anymore, so the best way to do this in iOS 15 is to set the value in the init
function and not in onAppear
.
Picker in Menu with Section and Label doesn't work
You can put multiple Pickers in a Menu, each with a subset of the available values, and they’ll all work as expected:
Menu {
// First section, with values 0–2
Picker(selection: $num) {
ForEach(0..<3, id: \.self) { i in
Text("Number: \(i)").tag(i)
}
} label: {
EmptyView()
}
// Second section, with values 3–5
Picker(selection: $num) {
ForEach(3..<6, id: \.self) { i in
Text("Number: \(i)").tag(i)
}
} label: {
EmptyView()
}
} label: {
Text("selected Number = \(num)")
}
SwiftUI will even stick a separator between the Pickers automatically.
SwiftUI Picker not changing selection value
Here is an approach for you:
struct ContentView: View {
@State private var selection: PickerType = PickerType.none
var body: some View {
OrderPicker(selection: $selection)
}
}
struct OrderPicker: View {
@Binding var selection: PickerType
var body: some View {
Form {
Picker("Order in list", selection: $selection) {
ForEach(PickerType.allCases, id: \.self) { item in
Text(item.rawValue)
}
}
.pickerStyle(WheelPickerStyle())
.onChange(of: selection, perform: { newValue in
print(newValue.rawValue, newValue.intValue)
})
}
}
}
enum PickerType: String, CaseIterable {
case none, first, second, third
var intValue: Int {
switch self {
case .none: return 0
case .first: return 1
case .second: return 2
case .third: return 3
}
}
}
Related Topics
How to Correctly Do Up an Adjustable Split View in Swiftui
Xcode 6, Swift and Mock Verification Without Exceptions
How Convert a *Positive* Number into an Array of Digits in Swift
How to Implement a Billboard Effect (Lookat Camera) in Realitykit
Gmail API: How to Send Attachments to The Drafts on Swift
How to Use a Protocol with Optional Class Methods in an Extension with Generic in Swift
Swift: No Idea How to Get Back the Selected Value from a Popover to the Calling Controller
How to Pass Image Value to The Imageslideshow Using Swift
Provide Simple Method to Get Current Speed (Implementing Speedometer)
How to Convert a Computed Value to a Literal for Enum Initialization
How to Access Content View's Elements Later in Swiftui
How to Add a Move Back to User Location Button in Swiftui
Swiftui Reorder List Dynamic Sections from Another View
Can't Use In/Contains Operator with Collection'
Adding Animation to Tabviews in Swiftui When Switching Between Tabs
When to Call Activatesession() on Wcsession Object
Get the Type of Anyobject Dynamically in Swift
Type Check Operator (Is) for Check VS Homogenous Protocol: Why Can This Be Done for Optionals