作者:Dariel
原文链接:https://www.ctolib.com/topics-137696.html
1.简单的实现
我们都知道 TableView 的刷新动效是设置在 tableView(_:,willDisplay:,forRowAt:) 这个方法中的。
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.alpha = 0;
UIView.animate(withDuration: duration, delay: delayFactor * Double(indexPath.row), options: [], animations: {
cell.alpha = 1
}, completion: nil)
}
这样一个简单的淡入效果就OK了,但这样显然不够优雅,我们如果要在多个TableView使用这个效果该怎样封装呢?
2.使用工厂设计模式进行封装
2.1 creator(创建者):Animtor,用来传入参数和设置动画
typealias Animation = (UITableViewCell, IndexPath, UITableView) -> ()
final class Animator {
private var hasAnimatedAllCells = false
private let animation: Animation
init(animation: @escaping Animation) {
self.animation = animation
}
func animate(cell: UITableViewCell, at indexPath: IndexPath, in tableView: UITableView) {
guard !hasAnimatedAllCells else {
return
}
animation(cell, indexPath, tableView)
}
}
2.2 product(产品):AnimtionFactory,用来设置不同的动画类型
enum AnimationFactory {
static func makeFade(duration: TimeInterval, delayFactor: Double) -> Animation {
return {cell, indexPath, _ in
cell.alpha = 0;
UIView.animate(withDuration: duration, delay: delayFactor * Double(indexPath.row), options: [], animations: {
cell.alpha = 1
}, completion: nil)
}
}
static func makeLeft() -> Animation {
return {cell, indexPath, _ in
cell.frame = CGRect(x: cell.frame.size.width, y: cell.frame.origin.y, width: cell.frame.size.width, height: cell.frame.size.height)
UIView.animate(withDuration: 0.5, delay: 0.05 * Double(indexPath.row), options: [], animations: {
cell.frame = CGRect(x: 0, y: cell.frame.origin.y, width: cell.frame.size.width, height: cell.frame.size.height)
}, completion: nil)
}
}
static func makeDamping() -> Animation {
return {cell, indexPath, _ in
cell.transform = CGAffineTransform(scaleX: 1, y: 0)
UIView.animate(withDuration: 0.5, delay: 0.05, usingSpringWithDamping: 1, initialSpringVelocity: 25, options: [], animations: {
cell.transform = CGAffineTransform(scaleX: 1, y: 1)
}, completion: nil)
}
}
static func makeDampingAndFade() -> Animation {
return {cell, indexPath, _ in
cell.transform = CGAffineTransform(scaleX: 1, y: 0)
UIView.animate(withDuration: 0.5, delay: 0.05 * Double(indexPath.row), usingSpringWithDamping: 1, initialSpringVelocity: 25, options: [], animations: {
cell.transform = CGAffineTransform(scaleX: 1, y: 1)
}, completion: nil)
}
}
}
将所有的动画设置封装在Animation的闭包中。
最后我们就可以在tableview:(_:,willDisplay:,forRowAt:)这个方法中使用如下代码,就实现最终效果
let animation = AnimationFactory.makeFade(duration: 0.5, delayFactor: 0.05)
let animator = Animator(animation: animation)
animator.animate(cell: cell, at: indexPath, in: tableView)
最终效果
注:原作者在Animator中animate方法中有一句
hasAnimatedAllCells = tableview.isLastVisibleCell(at: indexPath)
网友评论