Fab
Fab

Reputation: 1564

How to keep a view always centered independently from the size of the left view

I have a simple HStack containing a few views and I would like to keep one of the views ("Center") always centered. The size of the left view can change dynamically.

struct ExperimentView: View {
   var body: some View {
       HStack() {
           Text("A")
            .background(.red)
        
           Spacer()
        
           Text("Center")
            .background(.yellow)
           
           Spacer()
        
           Button("B1") {
            
           }
           Button("B2") {
            
           }
      }        
   }
}

The Center view is not centered and moves to the right depending on the size of Text. I have tried something using alignmentGuide but I had no success.

Upvotes: 0

Views: 64

Answers (1)

vadian
vadian

Reputation: 285039

A possible way is to wrap the "Center" text and the other views in a ZStack

struct ExperimentView: View {
    var body: some View {
        ZStack {
            Text("Center")
                .background(.yellow)

            HStack {
                Text("A")
                    .background(.red)
                Spacer()
                
                Button("B1") { }
                Button("B2") { }
            }
        }
    }
}

But this will not prevent the objects from overlapping if A becomes too wide.

Upvotes: 1

Related Questions