SwiftUI如何将图片固定在屏幕右上角?
如何将SwiftUI中的图片固定在屏幕右上角?
不需要必须用Geometry Reader,用SwiftUI的ZStack布局就能轻松实现,而且更简洁。当然如果一定要用Geometry Reader也可以,下面分别给出两种方案:
方案一:用ZStack对齐(推荐新手使用)
通过设置ZStack的对齐方式为.topTrailing,就能让目标图片自动固定在右上角,同时不影响其他内容布局:
ZStack(alignment: .topTrailing) { // 背景图铺满整个屏幕 Image("OnBoardingBackground") .resizable() .scaledToFill() .ignoresSafeArea() // 固定在右上角的图片,加padding避免贴紧边缘 Image("SignInImage") .resizable() .scaledToFit() .padding() // 原来的内容区域,通过Spacer把内容往下移,不遮挡右上角图片 VStack { Spacer() Text("Get Started") .font(.largeTitle) .fontWeight(.heavy) .fontWidth(.expanded) .fontDesign(.monospaced) Spacer() Text("Find community within your community") .font(.subheadline) .fontWeight(.heavy) .fontWidth(.standard) .multilineTextAlignment(.center) .fontDesign(.monospaced) .frame(width: 200) Divider() // 可继续添加底部内容 } }
方案二:用Geometry Reader手动定位
如果你想尝试Geometry Reader,可以通过它获取屏幕尺寸,手动设置图片的位置:
GeometryReader { geo in ZStack { Image("OnBoardingBackground") .resizable() .scaledToFill() .ignoresSafeArea() Image("SignInImage") .resizable() .scaledToFit() // 手动设置位置:距离右边20pt,顶部20pt .position( x: geo.size.width - 20, y: 20 ) // 原来的内容区域 VStack { Spacer() Text("Get Started") .font(.largeTitle) .fontWeight(.heavy) .fontWidth(.expanded) .fontDesign(.monospaced) Spacer() Text("Find community within your community") .font(.subheadline) .fontWeight(.heavy) .fontWidth(.standard) .multilineTextAlignment(.center) .fontDesign(.monospaced) .frame(width: 200) Divider() } } }
两种方案都能实现需求,方案一的布局逻辑更符合SwiftUI的设计理念,代码也更简洁,更适合新手。
内容的提问来源于stack exchange,提问作者Ben gann
相关产品推荐
相关产品推荐

