SwiftUI DatePicker : Hiding Label


DatePicker by default contains a label which is a string but what if you want to provide your own view as a label and not display the default label 🤔

We can set the label as an empty string but that would not solve the problem entirely, let’s try that first.

We will wrap our DatePicker inside a HStack and provide our own Text View, which will serve as a label for the view. We will also set DatePicker label string to be empty.
struct DatePickerExample: View {
    @State private var date = Date()
    
    var body: some View {
        HStack {
            Text("Pick a date")
            DatePicker(
                "", 
                selection: $date, 
                displayedComponents: [.date, .hourAndMinute])
                .padding()
                .datePickerStyle(.compact)
                .padding()
        }
    }
}



Notice that our Text view is pushed out and there is space between Text view and DatePicker.

If we use .labelsHidden modifier then we can hide label completely which will remove the label from DatePicker view hierarchy. To show the difference, we will put two HStack inside a VStack to see the effect.
struct DatePickerExample: View {
    @State private var date = Date()
    
    var body: some View {
        VStack {
            HStack {
                Text("LabelsHidden")
                DatePicker(
                    "", 
                    selection: $date, 
                    displayedComponents: [.date, .hourAndMinute])
                    .padding()
                    .datePickerStyle(.compact)
                    .padding()
                    .labelsHidden()
                    .border(Color.cyan)
            }
            
            HStack {
                Text("Empty Label")
                DatePicker(
                    "", 
                    selection: $date, 
                    displayedComponents: [.date, .hourAndMinute])
                    .padding()
                    .datePickerStyle(.compact)
                    .padding()
                    .border(Color.cyan)
            }
        }.padding()
    }
}