1

I'm trying to simply add a DatePicker in SwiftUI to a navigation bar, this is my code:

struct ContentView: View {
    @State var selectedDate: Date = Date()
    
    var body: some View {
        NavigationView {
            VStack {
                Text("Hello, world!")
            }
            .navigationBarItems(
                leading: DatePicker(selection: $selectedDate, displayedComponents: .date) {}
            )
        }
    }
}

This works fine on iOS but on the iPad simulator when I click the date picker nothing happens and the console prints some layout constraint error and this:

UIDatePicker 0x7fc3511141d0 is being laid out below its minimum width of 280. This may not look like expected, especially with larger than normal font sizes.

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Ludyem
  • 1,709
  • 1
  • 18
  • 33

1 Answers1

2

It looks like the leading position in the navigation bar is occupied by the sidebar button. As an alternative to .navigationBarItems, you can use toolbar and specify a placement:

struct ContentView: View {
    @State var selectedDate = Date()
    
    var body: some View {
        NavigationView {
            VStack {
                Text("Hello, world!")
            }
            .toolbar {
                ToolbarItem(placement: .principal) {
                    DatePicker(selection: $selectedDate, displayedComponents: .date) {}
                }
            }
        }
    }
}

Note: I used the .principal placement because it seems there's no enough space to render a DatePicker as .navigationBarLeading. However, feel free to try other placements.

pawello2222
  • 46,897
  • 22
  • 145
  • 209