使用.edgesIgnoringSafeArea(.top)导致SwiftUI全屏垂直滚动内容收缩
解决SwiftUI全屏垂直滚动页面添加edgesIgnoringSafeArea后宽度收缩问题
问题出在你把.edgesIgnoringSafeArea(.top)加在了GeometryReader外部,这会导致GeometryReader获取的尺寸是扣除顶部安全区后的屏幕大小,进而让后续基于该尺寸计算的TabView宽高出现偏差,最终表现为内容宽度收缩。
你可以把忽略安全区的修饰符移到TabView内部的每个页面容器上,这样既能让内容填满顶部安全区,又不会影响GeometryReader获取完整的屏幕尺寸:
struct ViewA: View { let colors: [Color] = [ .red, .green, .blue, .gray ] var body: some View { GeometryReader { proxy in TabView { ForEach(colors, id: \.self) { color in ZStack { color VStack { Text("Hello World") } } .edgesIgnoringSafeArea(.top) // 移到页面容器上 } .rotationEffect(.degrees(-90)) .frame( width: proxy.size.width, height: proxy.size.height ) } .frame( width: proxy.size.height, height: proxy.size.width ) .rotationEffect(.degrees(90), anchor: .topLeading) .offset(x: proxy.size.width) .tabViewStyle( PageTabViewStyle(indexDisplayMode: .never) ) } } }
或者,如果你希望整个TabView都忽略顶部安全区,也可以把.edgesIgnoringSafeArea(.top)直接添加到TabView层级,而非GeometryReader外部:
struct ViewA: View { let colors: [Color] = [ .red, .green, .blue, .gray ] var body: some View { GeometryReader { proxy in TabView { ForEach(colors, id: \.self) { color in ZStack { color VStack { Text("Hello World") } } } .rotationEffect(.degrees(-90)) .frame( width: proxy.size.width, height: proxy.size.height ) } .frame( width: proxy.size.height, height: proxy.size.width ) .rotationEffect(.degrees(90), anchor: .topLeading) .offset(x: proxy.size.width) .tabViewStyle( PageTabViewStyle(indexDisplayMode: .never) ) .edgesIgnoringSafeArea(.top) // 添加到TabView层级 } } }
核心逻辑:GeometryReader的尺寸会受父视图的安全区设置影响,当你在它外部添加忽略安全区的修饰符时,它的可用空间会被调整,导致后续基于proxy.size计算的宽高不再匹配完整屏幕,旋转后就会出现内容收缩的问题。将忽略安全区的操作放在内部层级,能保证GeometryReader获取到完整的屏幕尺寸,从而让TabView的布局计算保持准确。
内容的提问来源于stack exchange,提问作者PrimeTimeTran
相关产品推荐
相关产品推荐

