5

Given an HStack like the following:

        HStack{
            Text("View1")

            Text("Centre")

            Text("View2")

            Text("View3")
        }

How can I force the 'Centre' view to be in the centre?

Confused Vorlon
  • 7,561
  • 1
  • 36
  • 40

2 Answers2

6

Here is possible simple approach. Tested with Xcode 11.4 / iOS 13.4

demo

struct DemoHStackOneInCenter: View {
    var body: some View {
        HStack{
            Spacer().overlay(Text("View1"))

            Text("Centre")

            Spacer().overlay(
                HStack {
                    Text("View2")
                    Text("View3")
                }
            )
        }
    }
}

The solution with additional alignments for left/right side views was provided in Position view relative to a another centered view

Asperi
  • 123,447
  • 8
  • 131
  • 245
  • that's an interesting approach. It does rather mess up the spacing between the views, but you can fix that with more spacers in the left/right HStacks and explicit spacing. – Confused Vorlon Jun 15 '20 at 14:42
3

the answer takes a handful of steps

  1. wrap the HStack in a VStack. The VStack gets to control the horizontal alignment of it's children
  2. Apply a custom alignment guide to the VStack
  3. Create a subview of the VStack which takes the full width. Pin the custom alignment guide to the centre of this view. (This pins the alignment guide to the centre of the VStack)
  4. align the centre of the 'Centre' view to the alignment guide

For the view which has to fill the VStack, I use a Geometry Reader. This automatically expands to take the size of the parent without otherwise disturbing the layout.

import SwiftUI


//Custom Alignment Guide
extension HorizontalAlignment {
    enum SubCenter: AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> CGFloat {
            d[HorizontalAlignment.center]
        }
    }

    static let subCentre = HorizontalAlignment(SubCenter.self)
}

struct CentreSubviewOfHStack: View {
    var body: some View {
        //VStack Alignment set to the custom alignment
        VStack(alignment: .subCentre) {
            HStack{
                Text("View1")

                //Centre view aligned
                Text("Centre")
                .alignmentGuide(.subCentre) { d in d.width/2 }

                Text("View2")

                Text("View3")
            }

            //Geometry reader automatically fills the parent
            //this is aligned with the custom guide
            GeometryReader { geometry in
                EmptyView()
            }
            .alignmentGuide(.subCentre) { d in d.width/2 }
        }
    }
}

struct CentreSubviewOfHStack_Previews: PreviewProvider {
    static var previews: some View {
        CentreSubviewOfHStack()
            .previewLayout(CGSize.init(x: 250, y: 100))
    }
}

Centre is in the centre

Confused Vorlon
  • 7,561
  • 1
  • 36
  • 40