如何消除SwiftUI中Text组件.popover的默认垂直内边距?
iOS 16 SwiftUI Popover 消除Text组件多余垂直内边距问题
问题描述
为文本字段创建带错误提示的popover时,使用Text组件会导致popover顶部和底部出现多余垂直内边距:
.popover( isPresented: $isValid, attachmentAnchor: .point(.center), arrowEdge: .bottom ) { Text("Some error text") .presentationCompactAdaptation(.popover) }

但使用固定尺寸组件(如Rectangle)时,popover不会出现额外内边距:
.popover( isPresented: $isValid, attachmentAnchor: .point(.center), arrowEdge: .bottom ) { Rectangle().fill(.yellow) .frame(width: 100, height: 100) .presentationCompactAdaptation(.popover) }

仅Text组件存在此问题,不想通过复杂自定义扩展解决,目标系统为iOS 16。
解决方案
方案1:使用fixedSize()约束Text尺寸
给Text添加.fixedSize(),让popover贴合Text的实际内容尺寸,自动消除多余内边距:
.popover( isPresented: $isValid, attachmentAnchor: .point(.center), arrowEdge: .bottom ) { Text("Some error text") .fixedSize() .presentationCompactAdaptation(.popover) }
方案2:手动调整内边距
如果需要更灵活的控制,可通过负内边距抵消默认的多余间距(数值可根据实际内容微调):
.popover( isPresented: $isValid, attachmentAnchor: .point(.center), arrowEdge: .bottom ) { Text("Some error text") .padding(.vertical, -8) // 负内边距抵消默认间距 .presentationCompactAdaptation(.popover) }
方案3:用容器包裹并约束尺寸
使用VStack包裹Text,同时设置容器的高度约束,避免popover自动添加额外空间:
.popover( isPresented: $isValid, attachmentAnchor: .point(.center), arrowEdge: .bottom ) { VStack(spacing: 0) { Text("Some error text") } .frame(minHeight: nil, idealHeight: nil, maxHeight: .infinity, alignment: .top) .presentationCompactAdaptation(.popover) }
内容的提问来源于stack exchange,提问作者Kenzot
相关产品推荐
相关产品推荐

