【Swift】tableViewでセルを表示する
完成画面
必要なプロセス
プロセス - StoryBoard編
- tableView、tableViewCellを配置
- tableViewのIdentifierを設定
- tableViewにOutletで紐付け
- tableViewCellの上にUILabelを配置
- UILabelのtagを1に設定
1.
2.
5.
プロセス - ViewContoller編
- UITableViewDelegate,UITableViewDataSourceを記述
- viewDidLoad()でdelegate,datasourceを宣言..?
- 表示したいテキストを配列で用意(今回はtextという名前の配列)
- セルの表示に必要な4つの関数を用意(numberOfSections、numberOfRowsInSection、cellForRowAt、heightForRowAt)
1.
numberOfSections:セルを分類するカテゴリの数
今回は分類しないので return 1
numberOfRowsInSection:セルの数
text配列の要素数を指定
cellForRowAt:セルを生成に関わる関数
StoryBoardで設定したセルのIdentifierを記述
//で設定したtagでUILabelを生成(今回は1)
heightForRowAt:1つのセルの高さ
お好みで
ソースコード
import UIKit class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var tableView: UITableView! let text = ["one","two","three","four","five","six"] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self // Do any additional setup after loading the view, typically from a nib. } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return text.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let textLabel = cell.viewWithTag(1) as! UILabel textLabel.text = text[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 62 } }
※補足:セル上にテキストを表示させる方法について
セルにテキストを表示する場合、
- 直接代入:cell.textLabel?.text = “文字列”
- UILabel:cell.viewWithTag() as! UILabel
- カスタムセル
の3通り。
今回は、セルの上に配置したUILabelで、セルにテキストを表示させた。
注意点としては、セルの配置したUILabelを紐付けすることができないこと。
ImageViewはかろうじて配置できるが、それ以外はおそらく不可能。
なので、tagを指定し、cell.viewWithTagによって、tagで指定したUI部品を変数で生成する必要がある。