SwiftUI 将图像固定在屏幕右上角并根据设备大小调整大小

bai*_*ain 2 image constraints autosize swiftui

我只是在学习 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)

        }
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

E.C*_*oms 6

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

然后为此容器分配对齐方式。

VStack的frame中的宽高需要使用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
    }
Run Code Online (Sandbox Code Playgroud)