1
1

More than 3 years have passed since last update.

[Swift5] セルの選択状態をカスタムする

Posted at

はじめに

UITableViewCellを使用しているときなどに、選択状態によって背景色やセル上のviewの表示/非表示を切り替えたいときがあると思います。
便利なメソッドがあるのでご参考までに。
内容が間違っていたり、もっと便利なやり方があればぜひ教えていただけると幸いです。

実装方法

結論、setSelected(_:animated:)を使用するだけです。
以下のコードは、カスタムなUITableViewCellの選択状態によって背景色とラベルの表示/非表示を切り替えています。
selectedプロパティがセルの選択状態を持っているので、簡単に処理を切り替えられます。

import UIKit

class CustomCell: UITableViewCell {

    @IBOutlet private weak var titleLabel: UILabel!
    @IBOutlet private weak var selectedLabel: UILabel! //セルが選択されているときに表示する

    override func prepareForReuse() {
        super.prepareForReuse()
        titleLabel.text = nil
        selectedLabel.text = nil
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        DispatchQueue.main.async {
            self.backgroundColor = selected ? .systemGray6 : .systemBackground
            self.contentView.backgroundColor = selected ? .systemGray6 : .systemBackground
            self.selectedLabel.isHidden = selected ? false : true
        }
    }
}

またsetHighlighted(_:animated:)メソッドもあり、選択されたときのハイライトをカスタムすることもできます。

似たようなプロパティとして、セルの選択状態を示すisSelectedisHighlightedがありますが、これをtrueにするとセルの外観をアニメーション遷移させることはできないので、セルの選択状態によってUIを遷移させるようなケースではsetSelected(_:animated:)を使用するのが推奨されているようです。

最後に

セルの選択状態を簡単にカスタムできることがわかりました。
カスタムなセルは利用シーンが多いので、また便利な方法を学んだら追記していきます。

参考文献

以下の情報を参考にしました。

1
1
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
1
1