0
0
iOS Swiftmobile~5 mins

Picker and DatePicker in iOS Swift

Choose your learning style9 modes available
Introduction

Pickers let users choose from a list or select a date easily. They make input simple and clear.

When you want the user to select one option from a list, like choosing a color or a fruit.
When you want the user to pick a date or time, like setting a birthday or an appointment.
When you want to save space on screen but still let users pick from many choices.
When you want to avoid typing errors by letting users pick from fixed options.
Syntax
iOS Swift
struct ContentView: View {
  @State private var selection = 0
  var body: some View {
    Picker("Choose an option", selection: $selection) {
      Text("Option 1").tag(0)
      Text("Option 2").tag(1)
    }
  }
}

// For DatePicker:
@State private var date = Date()
DatePicker("Select a date", selection: $date, displayedComponents: .date)

Use @State to keep track of the selected value.

Picker needs a label and a binding to the selected value.

Examples
A picker with string tags for fruit choices.
iOS Swift
Picker("Fruits", selection: $selectedFruit) {
  Text("Apple").tag("apple")
  Text("Banana").tag("banana")
  Text("Cherry").tag("cherry")
}
A date picker that only shows the date, not time.
iOS Swift
DatePicker("Birthday", selection: $birthday, displayedComponents: .date)
A date picker that only shows time selection.
iOS Swift
DatePicker("Meeting Time", selection: $meetingTime, displayedComponents: [.hourAndMinute])
Sample App

This app shows a wheel picker for fruits and a compact date picker for birthday. The selected fruit and date appear below each picker.

iOS Swift
import SwiftUI

struct ContentView: View {
  @State private var selectedFruit = "apple"
  @State private var birthday = Date()

  var body: some View {
    VStack(spacing: 20) {
      Picker("Select a fruit", selection: $selectedFruit) {
        Text("Apple").tag("apple")
        Text("Banana").tag("banana")
        Text("Cherry").tag("cherry")
      }
      .pickerStyle(.wheel)

      Text("You selected: \(selectedFruit.capitalized)")

      DatePicker("Select your birthday", selection: $birthday, displayedComponents: .date)
        .datePickerStyle(.compact)

      Text("Birthday: \(birthday.formatted(date: .abbreviated, time: .omitted))")
    }
    .padding()
  }
}

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}
OutputSuccess
Important Notes

Use .pickerStyle() to change how the picker looks (wheel, menu, segmented).

DatePicker can show date, time, or both using displayedComponents.

Always bind pickers to a state variable to track user choice.

Summary

Pickers let users choose from a list of options easily.

DatePickers let users select dates or times with a friendly interface.

Use state variables to keep track of what the user picks.