iOS SwiftUI中如何让Popover内的List自动适配尺寸?
SwiftUI Popover中List自动适配尺寸的解决方案
可行方案
核心思路是通过fixedSize(horizontal: true, vertical: true)让List根据内容自动计算尺寸,配合plain列表样式消除额外间距,无需手动设置固定宽高,同时完整保留swipeActions功能。
修改后的完整代码
import SwiftUI struct MainView: View { @State private var popoverIsPresented: Bool = false var body: some View { Button { popoverIsPresented = true } label: { Label("Plus", systemImage: "plus") } .popover(isPresented: $popoverIsPresented) { ListView() .presentationCompactAdaptation(.popover) } } } struct ListView: View { @State private var names: [String] = ["User 1", "User 2", "User 3", "User 4"] var body: some View { List { ForEach(names, id: \.self) { name in Text(name) .swipeActions(allowsFullSwipe: false) { Button { // 处理删除逻辑 } label: { Label("Delete", systemImage: "trash") } .tint(.red) } } } .listStyle(.plain) .scrollDisabled(true) .fixedSize(horizontal: true, vertical: true) } }
关键说明
fixedSize(horizontal: true, vertical: true):强制View根据自身内容尺寸渲染,而非填充父容器,这是让List适配Popover的核心设置。listStyle(.plain):移除分组列表默认的内边距、头部/尾部空白,避免List出现不必要的额外空间。scrollDisabled(true):因内容高度已完全适配Popover,禁用滚动可提升交互体验;若内容较多需要滚动,直接移除该设置即可,此时Popover会遵循系统默认最大高度,List内部可正常滚动且保留侧滑功能。
内容的提问来源于stack exchange,提问作者Ser Pounce
相关产品推荐
相关产品推荐

