Más contenido relacionado
La actualidad más candente (20)
Similar a ライブラリでよくある動きをUIKitのみでDIYしてみる(Part1) (15)
ライブラリでよくある動きをUIKitのみでDIYしてみる(Part1)
- 21. スクロールの検知時&表示されていないセルに対してUITableViewCell(PictureCell)のメソッドを実行する。
4. UITableViewに配置した画像にパララックス付与②
//スクロールが検知された時に実行される処理
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//パララックスをするテーブルビューの場合
if scrollView == parallaxTableView {
//画面に表示されているセルの画像のオフセット値を変更する
for indexPath in parallaxTableView.indexPathsForVisibleRows! {
setCellImageOffset(parallaxTableView.cellForRow(at: indexPath) as! PictureCell, indexPath: indexPath)
}
//(以下省略)
}
}
//まだ表示されていないセルに対しても同様の効果をつける
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let imageCell = cell as! PictureCell
setCellImageOffset(imageCell, indexPath: indexPath)
}
//UITableViewCell内のオフセット値を再計算して視差効果をつける
fileprivate func setCellImageOffset(_ cell: PictureCell, indexPath: IndexPath) {
let cellFrame = parallaxTableView.rectForRow(at: indexPath)
let cellFrameInTable = parallaxTableView.convert(cellFrame, to: parallaxTableView.superview)
let cellOffset = cellFrameInTable.origin.y + cellFrameInTable.size.height
let tableHeight = parallaxTableView.bounds.size.height + cellFrameInTable.size.height
let cellOffsetFactor = cellOffset / tableHeight
cell.setBackgroundOffset(cellOffsetFactor)
}
セル側のメソッドを呼び出す
UITableViewDelegate
UIScrollViewDelegate