0

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

kelalaka
  • 5,064
  • 5
  • 27
  • 44
  • As, I understand the DatePicker wants as much as space as possible, adding a `.frame(width:300)` can make the HStack on the center. This is a temprory solution for me, since the size of the title can be change.. – kelalaka Oct 08 '22 at 19:27

1 Answers1

2

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.

vacawama
  • 150,663
  • 30
  • 266
  • 294