SwiftUI中.presentationCompactAdaptation(.none)下popover尺寸适配问题
解决iOS 16.4中Popover适配多行文本高度的问题
当在iOS 16.4中使用.presentationCompactAdaptation(.none)实现紧凑屏幕的Popover时,多行文本内容会因系统默认高度限制被截断。要让Popover自动适配文本高度,可通过以下方法实现:
核心思路
利用GeometryReader获取文本内容的实际尺寸,手动设置Popover的preferredContentSize,突破系统的高度限制。
示例代码
import SwiftUI // 定义偏好键,用于传递内容高度 struct ContentHeightKey: PreferenceKey { static var defaultValue: CGFloat = 0 static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } } struct TestView: View { @State private var isPopoverOpen = false var body: some View { Button("打开Popover") { isPopoverOpen.toggle() } .popover(isPresented: $isPopoverOpen) { Text("这里是一段需要多行显示的测试文本,用来验证Popover是否能自动调整高度以完整展示所有内容,不再出现截断的情况。") .fixedSize(horizontal: false, vertical: true) .padding() .background( GeometryReader { geo in Color.clear .preference(key: ContentHeightKey.self, value: geo.size.height) } ) .onPreferenceChange(ContentHeightKey.self) { height in DispatchQueue.main.async { // 设置Popover的首选尺寸,宽度可根据需求调整 UIApplication.shared.windows.first?.rootViewController?.preferredContentSize = CGSize(width: 320, height: height) } } .presentationCompactAdaptation(.none) } } }
说明
- 通过
ContentHeightKey偏好键,传递文本内容的实际高度值 - 使用
GeometryReader包裹文本,精准获取包含padding在内的完整内容尺寸 - 在高度值更新时,手动设置Popover的
preferredContentSize,确保高度完全匹配文本内容 - 宽度可根据需求自定义,比如设置为固定值或基于屏幕宽度动态计算
内容的提问来源于stack exchange,提问作者eric
相关产品推荐
相关产品推荐

