LoginSignup
13
14

More than 5 years have passed since last update.

複数選択できるUITableViewを実装する(Swift)

Last updated at Posted at 2017-11-15

概要

UITableViewはCellの複数選択をサポートしています。
ここではその簡単な実装例を紹介します。

スクリーンショット

ソースコード

UITableViewはStoryboard側で追加されていて、dataSourceとdelegateはViewControllerに接続されているとします。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.rightBarButtonItem = editButtonItem

        // 複数選択を有効にする
        tableView.allowsMultipleSelectionDuringEditing = true
    }

    override func setEditing(_ editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)
        tableView.isEditing = editing
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "Item \(indexPath.row)"
        return cell
    }
}

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("select - \(indexPath)")
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        print("deselect - \(indexPath)")
    }
}

ポイント

  • tableView.allowsMultipleSelectionDuringEditing = trueで複数選択を有効
  • 選択時にdidSelectRowAt、選択解除時にdidDeselectRowAtが呼ばれる
    • 選択中のindexPathのリストを保持したい場合は、ここで配列に追加/削除を行います

環境

  • Xcode 9.1
  • Swift 4.0

以上、Cellの複数選択ができるUITableViewの実装メモでした。
今回試したコードはこちらに置いておきます

13
14
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
13
14