SwiftUI实现覆盖屏幕下半部分的RoundedRectangle方案咨询
解决SwiftUI中RoundedRectangle覆盖屏幕下半部分的问题
你需要调整VStack的布局逻辑,让RoundedRectangle占据剩余的屏幕空间,具体修改如下:
修改后的完整代码
// // Home.swift // MealMe // // Created by Ting Qu on 9/2/24. // import SwiftUI struct Home: View { var body: some View { Color.accentColor .ignoresSafeArea() .overlay { VStack(spacing: 0) { // 移除VStack默认间距 HStack{ Text("Hi Grace") .font(.title) .bold() Spacer() Image(uiImage: UIImage(named: "AppIcon")!) .resizable() .scaledToFill() .clipShape(Circle()) .overlay( Circle() .stroke(Color.white, lineWidth: 2).shadow(radius: 4) ) .frame(width: 42, height: 42) } .padding() HStack{ Text("August") .bold() Spacer() Image("Calendar") } .padding([.top, .horizontal]) ScrollView(.horizontal, showsIndicators: false){ HStack{ ForEach(1...7, id:\.self){ index in if index == 2{ singlePickedDate(isSelected: true) } else{ singlePickedDate(isSelected: false) } } } } .scrollBounceBehavior(.basedOnSize) .padding(.bottom) // 给日期栏底部加一点间距 // 添加Spacer让圆角矩形占据剩余空间 Spacer() RoundedRectangle(cornerRadius: 25) .fill(Color.white) .ignoresSafeArea(.container, edges: .bottom) // 覆盖底部安全区域 .frame(maxHeight: .infinity) // 强制占满可用高度 } } } } #Preview { Home() }
关键修改说明
- 给
VStack设置spacing: 0,避免默认间距导致布局错位 - 在RoundedRectangle前添加
Spacer(),将上方内容顶起,让圆角矩形自动填充剩余的屏幕空间 - 给RoundedRectangle添加
frame(maxHeight: .infinity),确保它能占满所有可用的垂直空间 - 加上
ignoresSafeArea(.container, edges: .bottom),让圆角矩形覆盖屏幕底部的安全区域,避免出现留白
内容的提问来源于stack exchange,提问作者Ting Qu
相关产品推荐
相关产品推荐

