Swift テーブルビュー

はじめに

入社2年目ののむそんが、修行のためswiftの勉強成果を垂れ流すお

今日はテーブルビューについてまとめるお

  • ビューを生成
  • テーブルにセルを表示
  • テーブルのセルタイプを理解
  • テーブルのデリゲートメソッドとデータソースメソッドを理解する
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//初期値設定 myItems:セル内文字 myTableView:テーブルビュー格納用の変数 cellIdentifer:セル識別子
    private let myItems:NSArray = ["TEST1", "TEST2", "TEST3"]
    private let myTableView = UITableView()
    private let cellIdentifier = "myCell"
    
    override func viewDidLoad() {
        super.viewDidLoad()
//ビューの位置、サイズを設定
        myTableView.frame = CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight)
//識別子の設定
        myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
//デリゲートの設定
        myTableView.dataSource = self
        myTableView.delegate = self

//ビューにテーブルビューを追加
        self.view.addSubview(myTableView)
    }



//セルをタッチした時のアクション タッチした瞬間のみセルの色が変化する
//delegate :UITableViewDelegate
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//セルの0番目のみセルの色がそのままになる。コメントアウト
//        if indexPath.row == 0 {
//            return
//        }
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        print("Num: \(indexPath.row)")
        print("Section: \(indexPath.section)")
        print("Value: \(myItems[indexPath.row])")
    }
//セクションの名前を指定
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "セクションナンバー \(section)"
    }
//セクションの中のセル数を指定
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myItems.count
    }
//セクション数を指定
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//セクションの数だけセル数(row)が増える 3x10=30個
        return 10
    }
//画面上にあるセルは画面外に消えると使い回される。使い回すための処理を追加
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //cellは使い回される(1画面分のみ。画面外に消えたものは下に)
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
        
        cell.textLabel?.text = "\(myItems[indexPath.row])"
        return cell
    }


補足

下記の通り必須で呼び出す必要があるメソッドがある UITableViewDataSource の場合

    public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

なお、呼び出す必要があるかどうかは、メソッドがオプショナル(optional)かどうかで判断する。

書くの疲れたおー◟꒰◍´Д‵◍꒱◞