作者:Dariel
原文鏈接:https://www.ctolib.com/topics-137696.html
1.簡單的實(shí)現(xiàn)
我們都知道 TableView 的刷新動(dòng)效是設(shè)置在 tableView(_:,willDisplay:,forRowAt:) 這個(gè)方法中的。
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)
}
這樣一個(gè)簡單的淡入效果就OK了,但這樣顯然不夠優(yōu)雅,我們?nèi)绻诙鄠€(gè)TableView使用這個(gè)效果該怎樣封裝呢?
2.使用工廠設(shè)計(jì)模式進(jìn)行封裝
2.1 creator(創(chuàng)建者):Animtor,用來傳入?yún)?shù)和設(shè)置動(dòng)畫
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(產(chǎn)品):AnimtionFactory,用來設(shè)置不同的動(dòng)畫類型
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)
}
}
}
將所有的動(dòng)畫設(shè)置封裝在Animation的閉包中。
最后我們就可以在tableview:(_:,willDisplay:,forRowAt:)這個(gè)方法中使用如下代碼,就實(shí)現(xiàn)最終效果
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)