SwiftUI中ScrollView滚动时如何保持顶部背景颜色一致
ScrollView弹性滚动时顶部避免白色背景的解决办法
问题
ScrollView顶部有绿色背景视图,在保留弹性滚动效果的前提下,向下滚动(内容上移)时会露出白色背景,需要保持背景颜色一致。
未滚动状态:
滚动时状态:
当前代码:
NavigationView { GeometryReader { proxy in ScrollView(showsIndicators: false) { VStack(spacing: 19) { VStack { // 带绿色背景的视图 // 自定义代码 }.frame(height: proxy.safeAreaInsets.top + 171, alignment: .top) .frame(minWidth: 0, maxWidth: .infinity) .background(Color.PRIMARY_BACKGROUND) // 其他内容代码 } } } }
解决方法
方案1:给ScrollView设置同色背景
ScrollView默认背景为白色,弹性滚动时会露出,直接给ScrollView添加和顶部视图一致的背景色即可:
NavigationView { GeometryReader { proxy in ScrollView(showsIndicators: false) { VStack(spacing: 19) { VStack { // 带绿色背景的视图 // 自定义代码 }.frame(height: proxy.safeAreaInsets.top + 171, alignment: .top) .frame(minWidth: 0, maxWidth: .infinity) .background(Color.PRIMARY_BACKGROUND) // 其他内容代码 } } // 添加此行,设置ScrollView背景色 .background(Color.PRIMARY_BACKGROUND) } }
方案2:给外层容器设置全局背景
如果需要整个页面背景统一,可将背景色设置到GeometryReader或NavigationView上:
NavigationView { GeometryReader { proxy in ScrollView(showsIndicators: false) { VStack(spacing: 19) { VStack { // 带绿色背景的视图 // 自定义代码 }.frame(height: proxy.safeAreaInsets.top + 171, alignment: .top) .frame(minWidth: 0, maxWidth: .infinity) // 其他内容代码 } } } .background(Color.PRIMARY_BACKGROUND) } // 若需要导航栏也同步背景,可补充以下设置 .navigationBarTitleDisplayMode(.inline) .toolbarBackground(Color.PRIMARY_BACKGROUND, for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar)
两种方案都能保留弹性滚动效果,方案1针对性解决ScrollView的问题,方案2适合全页面统一背景的场景,按需选择即可。
内容的提问来源于stack exchange,提问作者cleanrun
相关产品推荐
相关产品推荐

