LoginSignup
0
1

More than 3 years have passed since last update.

Swift UIViewControllerにtableViewを表示する(標準で用意されているセル採用パターン)

Last updated at Posted at 2020-06-03

ListViewController.swift


import UIKit

class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let dataList: Array = ["01","02"]
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self;
        tableView.dataSource = self;
        // Cell名の登録をおこなう.
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        // Do any additional setup after loading the view.
    }

    //追加③ セルの個数を指定するデリゲートメソッド(必須)
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }

    //追加④ セルに値を設定するデータソースメソッド(必須)
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // セルを取得する
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        // セルに表示する値を設定する
        cell.textLabel!.text = dataList[indexPath.row]
        return cell
    }
}

ListViewController.xib

tableViewを配置し、ListViewController.swiftとOutlet接続を行ってください。

ListViewController.swift@IBOutlet weak var tableView: UITableView!

ListViewController.swiftでコードで生成行う場合は.xibファイル自体不要です。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1