swiftuiswiftui-layoutswiftui-zstack

SwiftUI place around center object


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


Solution

  • 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