[Swift5] TableViewの実装メモ


TableViewメモ

・UITableViewDelegate, UITableViewDataSourceを継承する

実装するメソッド
・numberOfSections:セクション数
・numberOfRowsInSection:セクションあたり表示するセル行数
・heightForRowAt:高さ
・cellForRowAt:セル内処理

セル内の処理
・TableView.dequeueReusableCellでCell表示
・indexPath⇨return cellの繰返し処理

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var TableView: UITableView!
    @IBOutlet weak var textField: UITextField!

    var textArray = [String]()
    var imageArray = ["1","2","3","4","5"]

    override func viewDidLoad() {
        super.viewDidLoad()

        TableView.delegate = self
        TableView.dataSource = self
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return textArray.count
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 586
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = TableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        let imageView = cell.contentView.viewWithTag(1) as! UIImageView
        let label = cell.contentView.viewWithTag(2) as! UILabel

        label.text = textArray[indexPath.row]
        imageView.image = UIImage(named: imageArray[indexPath.row])

        return cell
    }

}