2018/05/10:Swift 4.1に対応しました
すぐ忘れてしまうので、備忘録として書いておく。
UITableView全体のセルを選択不可にする
最初からセルの選択はしないようにする、ということが決まっているのであれば、この設定をする。
Storyboard上ではUITableViewのSelection
の項目をNo Selection
にする。

コード上で設定する場合はallowsSelection
をfalseにする。
self.tableView.allowsSelection = false
UITableViewの特定のセルを選択不可にする
この設定にはいくつかパターンがある。
Storyboard上ではUITableViewCellのSelection
の項目をNone
にする。

ただし、この場合は該当のUITableViewCellクラス全体に影響が出る。
例えば、このセクションのこのセルだけ、という一部のセルの場合は使えない。
そういう場合はコードで設定する必要がある。
これは2番目のセルだけ選択不可にする場合。
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
の設定も必要。