LoginSignup
89
77

More than 5 years have passed since last update.

UITableViewのセルを選択不可にする方法

Last updated at Posted at 2016-04-06

2018/05/10:Swift 4.1に対応しました

すぐ忘れてしまうので、備忘録として書いておく。

UITableView全体のセルを選択不可にする

最初からセルの選択はしないようにする、ということが決まっているのであれば、この設定をする。

Storyboard上ではUITableViewのSelectionの項目をNo Selectionにする。

コード上で設定する場合はallowsSelectionをfalseにする。

swift
self.tableView.allowsSelection = false

UITableViewの特定のセルを選択不可にする

この設定にはいくつかパターンがある。

Storyboard上ではUITableViewCellのSelectionの項目をNoneにする。

ただし、この場合は該当のUITableViewCellクラス全体に影響が出る。

例えば、このセクションのこのセルだけ、という一部のセルの場合は使えない。
そういう場合はコードで設定する必要がある。

これは2番目のセルだけ選択不可にする場合。

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

    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    if indexPath.row == 1 {
        // セルの選択不可にする
        cell.selectionStyle = .none
    } else {
        // セルの選択を許可
        cell.selectionStyle = .default
    }

    return cell
}

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {

    switch indexPath.row {
        case 0:
            return indexPath
        // 選択不可にしたい場合は"nil"を返す
        case 1:
            return nil

        default:
            return indexPath
    }
}

これでOK。

余談

一部のブログでtableView(_:willSelectRowAt:)でnilを返すだけ、というのを見かけたけど、これはあくまでも選択時のハイライトは無効にしない。

この部分だけを設定して、セルを押し続けるとタップした直後はハイライトされないが、実際は選択されているように見えてしまう。

そのため、UITableViewCell.selectionStyle = UITableViewCellSelectionStyle.noneの設定も必要。

89
77
3

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
89
77