How do I align multiple views across multiple axes in SwiftUI?

Viewed 123

How do I lay out the following in SwiftUI?

Two vertically aligned circles with each circle having its own horizontally aligned rectangle

The two circles are centre aligned horizontally along the blue line, and the top circle is vertically aligned with its rectangle along the green line, with the bottom circle vertically aligned with the bottom rectangle along the red line.

There’s no nested HStack/VStack structure that can describe this. We think the solution has something to do with custom alignment guides, but all of the examples we could find stop short of this level of complexity.

1 Answers

It feels like your best bet in this situation would be to use a LazyVGrid. There's a tendency to think of grids being used for collections where we might have long lists of items, but they also work for a known, finite number of children, so I think they'd work here.

In essence, you have two columns of items – both can be flexible to a degree, but it sounds like your column of rectangles needs to expand more. So you could start off by trying something like:

let columns = [
  GridItem(.flexible(maximum: 120)), 
  GridItem(.flexible())
]

var body: some View {
  LazyVGrid(columns: columns) {
    // row 1, column 1
    RoundedRectangle(cornerRadius: 10)
      .frame(width: 100, height: 160)
    // row 1, column 2
    Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt enim in iaculis tincidunt. Nunc vitae imperdiet dolor")
    // row 2, column 1
    Circle()
      .frame(height: 100)
    // row 2, column 2
    Text("Integer vitae volutpat urna. Morbi vel pharetra dolor. Interdum et malesuada fames ac ante ipsum primis in faucibus. Mauris ornare a augue id cursus")
  }
}

The code above gives you something like:

Visual appearance of above code

I've not had the opportunity to use grids in this way myself yet, so haven't played around with all the customisation they offer, but it does feel like this might be the best way to get you what you want without worrying about alignment guides or preferences.

Related