SwiftUI引脚图像位于屏幕右上方,并根据设备大小调整大小

问题描述 投票:0回答:2

我只是学习Apple的SwiftUI,即使做基础也有点令人沮丧。我试图将图像显示在屏幕的右上角,但是默认情况下图像显示在屏幕中央。谁都知道我该怎么做。另外,我试图根据屏幕尺寸调整图像的大小,但是我在常规Swift中使用的旧的self.frame.width在Swift UI中不起作用。抱歉,但是这种在SwiftUI中编写代码的新方式对我来说很奇怪。

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)

        }
    }

  }
}
image constraints swiftui autosize
2个回答
1
投票

我也在学习,所以这可能不是理想的方法,但是我确实设法将图像固定在屏幕的右上角。

您可以从GeometryReader获取屏幕宽度。对齐使我发疯了一段时间,直到我意识到我可以给一个垫片一个框架以占据HStack的另一侧,然后它起作用。

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)
}

1
投票

您需要为外部容器添加一个框架,这里是VStack。

然后分配此容器的路线。

VStack框架中的宽度和高度需要使用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
    }
© www.soinside.com 2019 - 2024. All rights reserved.