#17 swift animate 動畫練習(四)

Stephen Huang
4 min readJul 7, 2021

--

UIViewPropertAnimator, UITableViewCell.VisibleCells 應用。

隨然是簡單的動畫應用,但是製造的畫面效果很棒。

用UIView.animate的程式碼如下:

override func viewWillAppear(_ animated: Bool) {
animateTable()
}

func animateTable() {
tableView.reloadData()

let cells = tableView.visibleCells
let tableHeight: CGFloat = tableView.bounds.size.height

for i in cells {
let cell: UITableViewCell = i as UITableViewCell
cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
}

var index = 0

for a in cells {
let cell: UITableViewCell = a as UITableViewCell
UIView.animate(withDuration: 1.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0) {
cell.transform = CGAffineTransform.init(translationX: 0, y: 0)
}
index += 1
}


}

cells代表所有可見的cell(visibleCells)。
用 For 迴圈,代表可見的所有 cell。

先將所有的 cell 降低到畫面最底部,然後在運用delay產生時間差
用damping 產生彈力,讓 cell 們依序從底下飛上來。

— — — — — — — — — — — — — — — — — — — — — — — — — — —

嘗試使用 UIViewPropertAnimator 來設置動畫。

func propertAnimation() {
tableView.reloadData()

let cells = tableView.visibleCells
let tableHeight = tableView.bounds.size.height

for i in cells {
let cell: UITableViewCell = i as UITableViewCell
cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
}

var index = 0

for a in cells {
let cell: UITableViewCell = a as UITableViewCell
let animate = UIViewPropertyAnimator(duration: 1.5, dampingRatio: 0.8) { //動畫期間跟彈力指數
cell.transform = CGAffineTransform(translationX: 0, y: 0) //動畫內容
}

animate.startAnimation(afterDelay: 0.08 * Double(index)) //延遲秒數
index += 1
}


}

在UIViewPropertyAnimator中,並沒有delay跟dampingRatio同時存在的用法,所以如果需要delay的話,就加在startAnimation的()裡面。

動畫練習(一)~(四)Github如下:

--

--

Stephen Huang
Stephen Huang

Written by Stephen Huang

Wish me luck on the way become iOS app developer!

No responses yet