You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中List Section内Lottie视图上方出现多余空白问题

问题解决方案

问题原因分析

出现多余空白的核心原因有两点:

  1. Section的空文本Header仍会占用默认高度空间
  2. LottieView作为UIViewRepresentable视图,默认intrinsicContentSize未适配SwiftUI布局,加上自定义视图的重复frame设置引发布局冲突

具体修复步骤

1. 替换Section的空Header为EmptyView

原代码中用Text("")作为Section header,SwiftUI仍会保留默认的header间距,改为EmptyView()并添加sectionHeaderTopPadding(0)彻底消除header空白:

Section {
    // 原有内容
} header: {
    EmptyView()
}
.sectionHeaderTopPadding(0)

2. 优化LottieView的布局适配

修改UIViewRepresentable的实现,确保动画视图能正确计算尺寸,避免额外空白:

struct LottieView: UIViewRepresentable {
    let loopMode: LottieLoopMode

    func updateUIView(_ uiView: LottieAnimationView, context: Context) {}

    func makeUIView(context: Context) -> LottieAnimationView {
        let animationView = LottieAnimationView(name: "smile_lottie")
        animationView.play()
        animationView.loopMode = loopMode
        animationView.contentMode = .scaleAspectFit
        animationView.animationSpeed = 0.7
        // 强制动画视图根据内容计算intrinsic size
        animationView.translatesAutoresizingMaskIntoConstraints = false
        return animationView
    }
}

3. 简化ParcelDetailHeader的frame设置

移除重复的frame嵌套,避免布局冲突:

struct ParcelDetailHeader: View {
    var body: some View {
        LottieView(loopMode: .loop)
            .scaleEffect(0.4)
            .frame(maxWidth: .infinity)
            .frame(height: 200)
            .background(Color("my_lottie_yellow"))
    }
}

4. 调整List行的额外间距(可选)

如果仍有细微空白,可给ParcelDetailHeader添加listRowSpacing(0):

ParcelDetailHeader()
    .listRowInsets(EdgeInsets())
    .listRowSpacing(0)

完整修复后的List代码

struct ParcelDetail: View {
    let item: ParcelItem
    @EnvironmentObject var order: Parcel

    var body: some View {
        List {
            Section {
                HStack{
                    Text(item.tracknumber)
                    Spacer()
                    Image(systemName: "shippingbox.fill")
                }
                ParcelDetailHeader()
                    .listRowInsets(EdgeInsets())
                    .listRowSpacing(0)
                Text(item.description)
                    .multilineTextAlignment(.trailing)
            } header:{
                EmptyView()
            }
            .sectionHeaderTopPadding(0)
        }
        .navigationTitle(item.name)
        .navigationBarTitleDisplayMode(.automatic)
    }
}

内容的提问来源于stack exchange,提问作者helloimbrando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:15:17