close
ChatGPT生成第1次的code再搭配blogger文章+微調
https://blog.csdn.net/weixin_41732253/article/details/104048437
self.header = LottieRefreshHeader(jsonFullnName: "PullToRefres.json") {
delegate.refresh()
}
self.scrollView.mj_header = self.header
import UIKit
import MJRefresh
import Lottie
final class LottieRefreshHeader: MJRefreshHeader {
private let jsonFullnName: String
private lazy var animationView: LottieAnimationView = {
// 初始化Lottie动画视图
let animationView = LottieAnimationView(name: jsonFullnName)
animationView.contentMode = .scaleAspectFill
animationView.loopMode = .playOnce
animationView.frame = CGRect(x: 0, y: 0, width: 120, height: 120)
return animationView
}()
init(jsonFullnName: String, refreshingBlock: @escaping MJRefreshComponentAction) {
self.jsonFullnName = jsonFullnName
super.init(frame: CGRect.zero) // 只能call frame,其它會Crash
self.refreshingBlock = refreshingBlock
}
required init?(coder: NSCoder) {
jsonFullnName = ""
super.init(coder: coder)
}
override func prepare() {
super.prepare()
// 将动画视图添加到header的视图中
addSubview(animationView)
}
override func placeSubviews() {
super.placeSubviews()
// 设置动画视图的位置,确保它居中显示
animationView.center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
}
// 开始刷新时播放动画
override func beginRefreshing() {
super.beginRefreshing()
animationView.play(fromProgress: 0, toProgress: 1, loopMode: .playOnce, completion: nil)
}
// 刷新结束时停止动画
override func endRefreshing() {
super.endRefreshing()
animationView.stop()
}
// 使用 scrollViewContentOffsetDidChange 来监听 contentOffset 变化
override func scrollViewContentOffsetDidChange(_ change: [AnyHashable : Any]?) {
super.scrollViewContentOffsetDidChange(change)
// 获取 scrollView 的 contentOffset,直接从 scrollView 访问
guard let scrollView = self.scrollView else { return }
let offset = scrollView.contentOffset
// 只在下拉时更新进度,确保 y 为负值(即下拉)
guard offset.y < 0 else { return }
switch state {
case .idle:
// 计算下拉的进度,使用 contentOffset.y 来得出进度
let progress = -offset.y / (scrollView.mj_h)
// 限制进度范围在0到1之间
let normalizedProgress = min(max(progress, 0), 1)
// 实时更新Lottie动画的进度
animationView.currentProgress = normalizedProgress
case .pulling:
animationView.play(fromProgress: 0, toProgress: 1, loopMode: .loop, completion: nil)
case .refreshing:
break
case .willRefresh:
break
case .noMoreData:
break
@unknown default:
break
}
}
}
全站熱搜