微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

UIRefreshControl 的 Lottie 动画子视图偏离中心

如何解决UIRefreshControl 的 Lottie 动画子视图偏离中心

我目前正在使用方形 Lottie 动画实现自定义 UIRefreshControl。我一直在努力解决我的 UIRefreshControl 的 Lottie 子视图的自动布局约束。我真的很感激任何建议。 我正在尝试使用以下代码使我导入的 (json) 动画与标准的普通 Apple UIRefreshControl 具有相同的大小和相同的位置

    lazy private var refreshControl: UIRefreshControl = {
    let rf = UIRefreshControl()
    rf.tintColor = .clear
    
    let loadingAnimation = Animation.named("My_Animation")
    let lottieView = AnimationView(animation: loadingAnimation)
    lottieView.play()
    lottieView.loopMode = .loop
    
    lottieView.contentMode = .scaleAspectFit
    lottieView.frame = rf.bounds      
    rf.addSubview(lottieView)

    return rf
}()

我的问题是这会导致我的动画在 UIRefreshControl 父视图中偏左而不是居中。我尝试使用以下约束:

lottieView.centerXAnchor.constraint(equalTo: rf.centerXAnchor).isActive = true
        lottieView.bottomAnchor.constraint(equalTo: rf.bottomAnchor).isActive = true
    lottieView.trailingAnchor.constraint(equalTo: rf.trailingAnchor).isActive = true
    lottieView.leadingAnchor.constraint(equalTo: rf.leadingAnchor).isActive = true

同样在其他教程和帖子中,我一直看到有人建议关闭 translatesAutoresizingMaskIntoConstraints,但是当我这样做时,动画会比屏幕大,并且大部分出现在屏幕外。

解决方法

对于其他为此苦苦挣扎的人,我继承了 UIRefreshControl 并在覆盖 init() 中调用了以下约束。似乎已经解决了这个问题:

    func setupLayout() {
    translatesAutoresizingMaskIntoConstraints = false
    animationView.frame = CGRect(x: UIScreen.main.bounds.midX - 160,y: 0,width: 320,height: 60)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。