UIScrollViewのアニメーションを待ってセルを取得する


「UIScrollViewのアニメーションが完了してからセルを取得して処理を実行したい...」という時がある。アニメーションが終わらないと、cellForRowがnilを返すのでどうにか待ちたい。そういう場合は以下のdelegateメソッドを利用する。

func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {

    // scrollToRowなどのアニメーションメソッドを呼ぶ前に退避した一時変数
    guard let activationIndexPath = self.activationIndexPath else {
        return
    }

    // スクロールのアニメーションが終了する前に処理をてもcellForRowがnilで返って来るので
    // アニメーション終了後のこのdelegateで処理を行う
    let cell = tableView.cellForRow(at: activationIndexPath)
    cell.executeYourTask()
}

(UITableViewDelegateはUIScrollViewDelegateを継承しているので、UITableView利用時でもtableView.delegate = selfとしていれば効いてくれる)

アニメーションが必要ない場合は、その場で処理を実行すればよい。

tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
let cell = tableView.cellForRow(at: indexPath)
cell.executeYourTask()