LoginSignup
5
5

More than 5 years have passed since last update.

UITableView の区切り線をカラフルにしたい!

Posted at

こんな感じにしたい!

colorful_separator2.png

すべての区切り線が同じ色で良い場合

全部同じで良い場合には、tableView.separatorColor で対応できます。
例えば、下記の例では、区切り線は赤色になります。

swift
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.separatorColor = .red
    }

ではそれぞれのセルで異なる色にするにはどうすれば良いか… :thinking:

カスタムセルでやる!

実際のところ、カスタムセルでも区切り線の色を個別に変えることはできなそうです :sob:
なので、自分で区切り線 (っぽい UIview) を作ることで対応します。

下記のように、セルの下部に区切り線に見えるような UIView を配置し、区切り線に見せかけます。

swift
class CustomTableViewCell: UITableViewCell {
    // 区切り線に見せかける view
    private let separator: UIView = {
        let view = UIView()
        return view
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.addSubview(separator)
        // contentView の最下部に高さの値を小さくして配置することで、区切り線に見せかける
        separator.translatesAutoresizingMaskIntoConstraints = false
        separator.heightAnchor.constraint(equalToConstant: 1).isActive = true
        separator.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
        separator.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
        separator.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setColor(color: UIColor) {
        separator.backgroundColor = color
    }
}

あとは、TableViewController 内で…。

tableView の区切り線を非表示にする (tableView.separatorStyle = .none)。

swift
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
        tableView.separatorStyle = .none
    }

カスタムセルを使うようにする。

swift
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
        cell.textLabel?.text = String(indexPath.row + 1)
        cell.setColor(color: colors[indexPath.row]) // 好きな色を設定する
        return cell
    }

これで、あたかもカラフルな区切り線ができたかのように見せることができます!

終わりに

今回の例のように区切り線をカスタマイズしたいという要望は少ないかもしれません。
ですが、どうしてもそういうデザインにしたいけれども、提供されているプロパティでは対処できない時には、
自分でそう見えるように工夫するという選択肢が頭の中にあると、解決に一歩近づけるのかなと思っています。

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