1
1

[備忘録] カスタムセルをコードで作成 (UITableViewCell)

Posted at

Storyboardを使わないカスタムセルの作成方法を、毎回調べてしまうので備忘録として残しておきます。

作成

  • UITableViewCellを継承したクラスを作成します。
  • initと入力して3番目くらいに出てくるinit(style:, reuseIdentifier:)を選択して、親クラスのを呼び出します。
  • 出てくる警告の[Fix]を押してrequired init?(coder: NSCoder)を補完します。
class CustomCell: UITableViewCell {
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setUpViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setUpViews() {
        // サブビューの配置を行う。
    }
}

override init(style:, reuseIdentifier:)内にサブビューのセットアップ処理を書きます。
required init?(coder:)は、Storyboardを使わない限り滅多に呼び出されることはありません。

サブビューの配置

selfではなく、contentViewにaddSubViewします。

    private func setUpViews() {
        サブビュー.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(サブビュー)
        NSLayoutConstraint.activate([
            サブビュー.xxAnchor.constraint(equalTo: contentView.xxAnchor),
            ...
        ])
    }

参考

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