いまいちなタイトルですが、ユーザ定義のセルクラスを用意しなくても、タグ番号指定でカスタムセルの要素にアクセスできますよという記事です。
Interface Builderにて、セルの上に乗せた要素にタグを設定します。0は設定しないでください。
viewWithTag()
を用いて設定したTag番号の要素にアクセスできます。要素がUIViewの場合、viewWithTag()の戻り値はもともとUIViewですのでキャスト不要です。
// UITableViewDataSource
// セル生成
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// イメージビューにアクセス
let imageView = cell.contentView.viewWithTag(1) as! UIImageView
imageView.image = UIImage(named:"pika.png")
// ビューにアクセス
let view = cell.contentView.viewWithTag(2)
view?.backgroundColor = .orange
return cell
}
なお、UICollectionViewでも同様なことができます。