问题描述
我目前正在使用方形 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)
}