bain
bain

Reputation: 355

SwiftUI pin Image to top right of screen and resize based on device size

I just learning Apple's SwiftUI and it is a bit frustrating even doing the basics. I am trying to get my image to the top right of my screen but the default has it showing up in the center of my screen. Anyone know how I can accomplish this. In addition, I tried to get the image to resize based on the screen size but the old self.frame.width that I used to use in regular Swift doesn't work in Swift UI. Sorry, but this new way of writing code in SwiftUI is very odd to me.

var body: some View {
    ZStack {
        //Define a screen color
        LinearGradient (gradient: Gradient(colors:[Color(ColorsSaved.gitLabDark),Color(ColorsSaved.gitLabLight)]),startPoint: .leading,endPoint: .trailing)

            //Extend the screen to all edges
            .edgesIgnoringSafeArea(.all)

        VStack(alignment: .trailing) {
            Image("blobVectorDark")
            .resizable()

            .edgesIgnoringSafeArea(.top)

           .frame(width: 60, height: 60)
               // .offset(x: , y: 20)

        }
    }

  }
}

Upvotes: 3

Views: 10802

Answers (2)

E.Coms
E.Coms

Reputation: 11531

You need to add a frame for the outer container, here is the VStack.

Then assign the alignment for this container.

The width and height in the frame of VStack needs to use geometryProxy.

GeometryReader{ (proxy : GeometryProxy) in  // New Code
              VStack(alignment: .trailing) {
               Image("blobVectorDark")
               .resizable()

              .edgesIgnoringSafeArea(.top)

              .frame(width: 60, height: 60)
            // .offset(x: , y: 20)

              }
.frame(width: proxy.size.width, height:proxy.size.height , alignment: .topLeading) // New Code
    }

Upvotes: 6

Fry
Fry

Reputation: 218

I'm learning too so this might not be the ideal way to do it, but I did manage to get the image to pin to the top right of the screen.

You can get the screen width from GeometryReader. The alignment was driving me nuts for a while, until I realized I could give a frame to a Spacer to take up the other side of an HStack, and then it worked.

var body: some View {
    GeometryReader { geometry in
        VStack {
            HStack {
                Spacer()
                .frame(width: geometry.size.width / 2)
                Image("blobVectorDark")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: geometry.size.width / 2)
            }
            Spacer()
        }

    }
    .edgesIgnoringSafeArea(.all)
}

Upvotes: 2

Related Questions