SwiftUI ScrollView导致视图塌陷(高度为0)问题

在SwiftUI中,如果一个没有固定尺寸的视图放进ScrollView,父视图没有给它明确的尺寸约束,它的高度将被计算为 0。

在显示Lottie动画时,发现计划显示的Lottie动画在Xcode预览中正常显示,但是在模拟器和真机中无法显示。

视图代码:

php 复制代码
LottieView(filename: "EmptyBanklet", isPlaying: true, playCount: 0, isReversed: false)
    .frame(maxHeight: 180)
    .frame(maxWidth: 500)

经过和其他可以显示的Lottie动画对比,并没有发现问题。

但是给该视图添加固定的frame后,Lottie动画可以正常显示:

php 复制代码
LottieView(filename: "EmptyBanklet", isPlaying: true, playCount: 0, isReversed: false)
    .frame(height: 100)
    .frame(maxHeight: 180)
    .frame(maxWidth: 500)

排查过程

起初判定原因是,我设置了忽略安全区域和填充样式的背景,导致图片在顶部显示。但当我设置整个视图为纯色背景时,仍然没有看到竖向填充的背景色。

php 复制代码
LottieView(filename: "EmptyBanklet", isPlaying: true, playCount: 0, isReversed: false)
    .frame(maxHeight: 180)
    .frame(maxWidth: 500)
    .background(Color.red)  // 检查视图

接着,我尝试使用Geometry获取视图的高度:

php 复制代码
GeometryReader { geo in
    LottieView(filename: "EmptyBanklet", isPlaying: true, playCount: 0, isReversed: false)
        .frame(maxHeight: 180)
        .frame(maxWidth: 500)
        .onAppear {
            print("SwiftUI 给 LottieView 的尺寸:", geo.size)
        }
}

Xcode输出:

scss 复制代码
SwiftUI 给 LottieView 的尺寸: (300.0, 10.0)

这表示SwiftUI给视图很小的高度,并且可以在视图中看到很小的LottieView动画。

当我删除GeometryReader后,LottieView再次消失。因此,开始怀疑LottieView动画过小导致的问题。

在LottieView代码中调试并打印UIKit尺寸:

javascript 复制代码
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    print("UIKit Lottie frame:", animationView.frame)
}

Xcode输出:

objectivec 复制代码
UIKit Lottie frame: (0.0, 0.0, 300.0, 0.0)

这表示视图的高度为0,因此看不到LottieView动画。

但是这个问题,在欢迎视图和设置视图的LottieView中并不能复现,因为欢迎视图和设置视图中的LottieView都是正常显示的,也就是说这个问题在这个视图中。

我通过排查法,将Lottie视图依次放在父视图中。经过层层排查,发现当LottieView视图放到ScrollView中后,视图塌陷(高度变为0)。

解决方案

因为这里的主要问题在于,ScrollView中的LottieView视图高度变成了0。

可以设置一个固定的高度,让LottieView视图显示出来:

php 复制代码
LottieView(filename: "EmptyBanklet", isPlaying: true, playCount: 0, isReversed: false)
    .frame(maxHeight: 100)
    .frame(maxHeight: 180)
    .frame(maxWidth: 500)

还有一个解决方案,那就是我想到类似的问题比较像Image图片,Image图片也是需要拉伸显示。

可以设置LottieView视图为 .scaledToFit(),这个方法可以在不设置固定高度的情况下,显示完整的视图大小。

php 复制代码
LottieView(filename: "EmptyBanklet", isPlaying: true, playCount: 0, isReversed: false)
    .scaledToFit()
    .frame(maxHeight: 180)
    .frame(maxWidth: 500)

因此,使用 .scaledToFit() 方法的方案更合适,可以解决ScrollView中视图塌陷(高度为0)的问题。

相关推荐
CocoaKier1 天前
苹果谷歌商店:如何监控并维护用户评分评论
ios·google·apple
iOS日常1 天前
iOS设备崩溃日志获取与查看
ios·xcode
wangruofeng2 天前
AI 助力 Flutter 3.27 升级到 3.38 完整指南:两周踩坑与实战复盘
flutter·ios·ai编程
iOS日常2 天前
Xcode 垃圾清理
ios·xcode
开心就好20252 天前
不越狱能抓到 HTTPS 吗?在未越狱 iPhone 上抓取 HTTPS
后端·ios
傅里叶3 天前
iOS相机权限获取
flutter·ios
zhangkai3 天前
flutter存储知识点总结
flutter·ios
齐生14 天前
网络知识点 - TCP/IP 四层模型知识大扫盲
笔记·ios
IT技术分享社区4 天前
数码资讯:iPhone 18 Pro,十大升级细节浮出水面
ios·手机·iphone
嵌入式学习菌4 天前
https不校验证书实现及https接口实现
ios·iphone