【Swift】xibを使ってUITableViewを実装する
はじめに
UITableViewを使用する際にカスタムセルを.xibを使用して実装する方法について書きます。
xibを使用することでカスタムセルのcalss内の記述をStoryboardベースで実装することができます。
この記事でやること
UITableViewCellのxibにあるLabelのテキストを変更する
実装
TableViewの追加
xibファイルを作成
UITableViewCellを選択、Also Create XIB fileにチェックを入れ、ファイルを作成する
Labelの追加
TableViewを作成
TableViewとコードをOutlet接続し、extensionに一般的なTableViewのコード()を書きます
ここで一般的なTableViewと違うのがRegisterを記述する点と
ViewController.swift
tableView.dataSource = self
tableView.delegate = self
// registerでxibをidentifierとして設定する
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
ここで設定したidentifierを使用する点です。
ViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
cell.titleLabel?.text = "aaa"
return cell
}
ビルドしてみる
これで冒頭の通りxibを使用してUITableViewCellのテキストを変更することができたかと思います。
もし参考になればLGTMくれると嬉しいです!
Author And Source
この問題について(【Swift】xibを使ってUITableViewを実装する), 我々は、より多くの情報をここで見つけました https://qiita.com/oskmr/items/f4e30d430209dbe9517c著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .