kelalaka
kelalaka

Reputation: 5636

Centering Item Inside Horizontal Stack with left and right views doesn't work with DatePicker

There was a similar question Center Item Inside Horizontal Stack that I followed the Asperi's basic answer that suited for me ( other answer did not worked, too).


struct HeaderTestView: View {
    
    @State private var currentDate = Date()
    
    var body: some View {
        ZStack {
            HStack {
                HStack {
                    Button(action: {
                    }) {
                        Image(systemName: "arrowtriangle.left.fill")
                    }
                }
                Spacer()
                
                HStack {
                    Button(action: {
                    }) {
                        Image(systemName: "arrowtriangle.right.fill")
                    }
                }
            }
            HStack {
                Text("Title")

                DatePicker("Date", selection: $currentDate, displayedComponents: [.date])
            }
        }
    }
}

My Center Item are a Text and a DatePicker, everything works as expected until the date picker is placed. The title of DatePicker is placed on the left and date is placed on the right.

Without the DatePicker

enter image description here

With the DatePicker

enter image description here

Any idea to solve this beautifully so that a Text and a DatePicker are close on the center while there are two HStacks that are adjested to on the left and right

Upvotes: 0

Views: 74

Answers (1)

vacawama
vacawama

Reputation: 154711

Add .fixedSize() to the HStack containing the Text view and DatePicker:

struct ContentView: View {
    
    @State private var currentDate = Date()
    
    var body: some View {
        ZStack {
            HStack {
                HStack {
                    Button(action: {
                    }) {
                        Image(systemName: "arrowtriangle.left.fill")
                    }
                }
                Spacer()
                
                HStack {
                    Button(action: {
                    }) {
                        Image(systemName: "arrowtriangle.right.fill")
                    }
                }
            }
            HStack {
                Text("Title")
                
                DatePicker("Date", selection: $currentDate, displayedComponents: [.date])
            }
            .fixedSize()  // here
        }
    }
}

or add .fixedSize() to the DatePicker.

Upvotes: 2

Related Questions