SwiftUI自适应高度Bottom Sheet后台恢复后高度归零问题
解决SwiftUI Bottom Sheet后台切换后高度重置为0的问题
问题根源在于@State变量detentHeight在应用切换后台时会被重置,重新进入应用时presentationDetents会优先使用初始值0,而PreferenceKey的高度回调可能未及时触发。以下是具体修复方案:
1. 用@SceneStorage持久化高度值
@SceneStorage会将值与当前场景绑定,后台切换或场景重启时不会丢失数据,替代原有的@State变量。
2. 修改BottomView代码
调整BottomView的状态存储逻辑,确保高度值被持久化,同时避免异常空白情况:
struct BottomView: View { // 用SceneStorage持久化高度,自定义唯一键名 @SceneStorage("bottomSheetDetentHeight") private var detentHeight: CGFloat = 0 var body: some View { Text("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.") .padding(40) .fixedSize(horizontal: false, vertical: true) .readHeight() .onPreferenceChange(HeightPreferenceKey.self) { newHeight in // 仅当新高度有效时更新存储值,避免初始0值覆盖已有数据 if newHeight > 0 { detentHeight = newHeight } } // 设置最小高度,防止高度为0时Bottom Sheet不可见 .presentationDetents([.height(max(detentHeight, 100))]) } }
3. 原有代码无需修改
原有的HeightPreferenceKey定义、ReadHeightModifier及readHeight扩展保持不变,它们仍负责正确计算视图的实际高度。
调整后,应用切换后台再返回时,detentHeight会从@SceneStorage中读取之前保存的有效高度,Bottom Sheet就能维持正确的自适应高度。
内容的提问来源于stack exchange,提问作者OuSS
相关产品推荐
相关产品推荐

