0

I have the following code in SwiftUI, where I use the .offset modifier to set specific positions for images in a ZStack. However, when I change to a different device format, the images move away from their intended positions. Is there a way to create constraints or improve this code to make the images maintain their positions properly across different device formats?

struct ContentView: View {
    var body: some View {
        ZStack {
            Image("bird")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .edgesIgnoringSafeArea(.all)
            Image(systemName: "camera.on.rectangle")
                .offset(x: 160, y: -380)
                .font(.largeTitle)
            Image(systemName: "heart")
                .offset(x: -160, y: 380)
                .font(.largeTitle)
                .foregroundColor(.red)
            Image(systemName: "square.and.arrow.up.on.square")
                .offset(x: -160, y: -380)
                .font(.largeTitle)
        }
    }
}

I would appreciate any help or suggestions on how to properly position these images using constraints or any other method to ensure their position consistency across different device formats in SwiftUI. Thank you.

Thanks.

Martin
  • 46
  • 9

1 Answers1

-1

In SwiftUI, you can use the alignmentGuide modifier along with GeometryReader to create more flexible layouts that adapt to different device sizes. This allows you to define constraints and alignment for your views.

struct ContentView: View {
    var body: some View {
        ZStack(alignment: .topLeading) {
            GeometryReader { geometry in
                Image("bird")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: geometry.size.width, height: geometry.size.height)
                    .edgesIgnoringSafeArea(.all)
                
                VStack {
                    Image(systemName: "camera.on.rectangle")
                        .font(.largeTitle)
                        .alignmentGuide(.topLeading) { d in d[.top] + d[.height] / 2 }
                    Spacer()
                    Image(systemName: "heart")
                        .font(.largeTitle)
                        .foregroundColor(.red)
                        .alignmentGuide(.bottomTrailing) { d in d[.bottom] - d[.height] / 2 }
                }
                
                Image(systemName: "square.and.arrow.up.on.square")
                    .font(.largeTitle)
                    .alignmentGuide(.bottomLeading) { d in d[.bottom] - d[.height] / 2 }
            }
        }
    }
}

By using GeometryReader, you can obtain the size of the available space and use it to calculate the desired offsets for each image. This way, the images will maintain their relative positions even when the device format changes.

Martin
  • 46
  • 9