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),
...
])
}
参考