SwiftUI place around center object

147 views Asked by At

Say the blue rectangle is in the center of the red rectangle, and the green needed to be on top and the yellow on the left.

How would one do this in SwiftUI with alignment guides? None of the sizes are known, but the yellow and blue height match, and green and blue width match.

enter image description here

1

There are 1 answers

0
magnuskahr On BEST ANSWER

I got help from https://swiftui-lab.com on twitter

With my helper method:

extension View {
    func overlay<Overlay: View>(alignment: Alignment, @ViewBuilder builder: () -> Overlay) -> some View {
        overlay(builder(), alignment: alignment)
    }
}

it can be done so:

Color.red
  .overlay(alignment: .bottom) {
    HStack(alignment: .top, spacing: 0) {
      Color.clear.frame(width: 0)
      Color.yellow
      .alignmentGuide(.top) { $0.height + 10 }
    }
  }
  .overlay(alignment: .trailing) {
    VStack(alignment: .leading, spacing: 0) {
      Color.clear.frame(height: 0)
      Color.blue
        .alignmentGuide(.leading) { $0.width + 10 }
    }
  }
  .padding(100) // padding given for the example