【Swift】TableViewを使ったパララックスアニメーション

 

解説

 

※注意

ソースコードが複雑で、僕もよくわかってない

 

・”パララックス”という視覚効果

↓参考動画

youtu.be

・セルをスクロールすると、セル内のImageViewがパララックスの視覚効果をもたらす

 

ストーリーボード

 

f:id:nekokichi_yos2:20181011141420p:plain

 

ソースコード

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
        
        tableView.reloadData()
        
        paralex()
        
    }
    
    //画像の視覚効果を実装する
    func paralex() {
        guard let tableViewRows = tableView.indexPathsForVisibleRows else { return }
        for indexPath in tableViewRows {
            //セルを生成
            guard let cell = tableView.cellForRow(at: indexPath) as? CustomCell else { continue }
            
            //indexPathに該当するセルのdraw(描く)area(領域)をCGRectで返す
            let rect = tableView.rectForRow(at:indexPath)
            //rectでtableViewに表示するための座標を読み込む
            let rectInTable = tableView.convert(rect, to: tableView.superview)
            //??
            let offset = rectInTable.origin.y + rectInTable.height / 2
            //tableViewの数だけoffsetを割る?
            let offsetRatio = offset / tableView.bounds.height
            
            //セルのimageViewのframe(描画後の座標)を取得
            var imageViewRect = cell.paralexImageView.frame
            
            //??
            imageViewRect.origin.y = offsetRatio * 100 * -1
            //??
            cell.paralexImageView.frame = imageViewRect
            
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 8
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 165
    }
    
    //スクロールした時に視覚を変化させる
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        paralex()
    }

}

 

ソースコード2

import UIKit

class CustomCell: UITableViewCell {
    
    //ImageViewで紐付けすると、エラーがでる
    //既にカスタムクラスにはimageViewがあるらしいから
    //同じ名前ではなくimageView以外の名前に推奨
    @IBOutlet weak var paralexImageView: UIImageView!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
}