LoginSignup
2
3

More than 3 years have passed since last update.

UITableViewCellの選択アニメーション

Last updated at Posted at 2020-06-18

設定画面などで複数の選択肢から一つを選択したときに、Cellにチェックマークをつけながらdeselectのアニメーションをする

tableView.indexPathForSelectedRow とかで選択中を判定すると、tableView.deselectRow をしたときに選択解除されてしまうのでCellの選択アニメーションがつけれない。なので変数で保持。

class TableViewController: UITableViewController {

    // 選択中のCellを保持しておく変数
    var selectedRow = 0

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        ...

        // selectedRowならCheckmarkをつける
        cell.accessoryType = selectedRow == indexPath.row ? .checkmark : .none

        ...
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // deselectのアニメーション
        tableView.deselectRow(at: indexPath, animated: true)

        // Checkmarkの切替
        let oldIndexPath = IndexPath(row: selectedRow, section: 0)
        selectedRow = indexPath.row
        tableView.cellForRow(at: oldIndexPath)?.accessoryType = .none
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
}
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3