Swift で UITableView の実装

Swift で UITableVIew を使ってみます。

手順

  1. StoryBoard で UITableView, UITableVIewCell を配置する。
  2. ViewControllerでは、UITableViewDataSource, UITableViewDelegateを継承し、初期処理でdeletegate,dataSourceの設定を行う。

 ※もちろんStoryBoardからの設定でも可 3. 必要なdelegateメソッドを実装する。以下実装例です。

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet var tableView: UITableView
    var items:Array<String> = ["one", "two", "three", "four"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.tableView.delegate = self
        self.tableView.dataSource = self;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        let cell: UITableViewCell =  tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell!
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        cell.textLabel.text = "\(self.items[indexPath.row])"
        cell.detailTextLabel.text = "Subtitle index : \(indexPath.row)"
        return cell
    }
    
    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        // 選択するとアラートを表示する
        let alert = UIAlertView(title: "alertTitle", message: "selected cell index is \(indexPath.row)", delegate: nil, cancelButtonTitle: "OK")
        alert.show()
        
    }

objective-c の頃とほとんど同じ手順で実装できます。 ただ、これだとcellのaccessoryTypeが効かない模様。 何か設定が足りない?betaだから??継続調査。。

色々触ってみたところ、TableViewの幅が画面を超えていただけのようでした。 試しに極端に短くしてシミュレータ上に表示しきれるようにするとちゃんと表示されました。

なお、画面にFitするようにするには、

  1. StoryBoard上でTableViewを貼り付け元のViewと同サイズにする
  2. TableVIewを選択し、pin をクリック(右下の |-□-| というやつ)
  3. Spacing to nearest neighbor で左右を固定

とすればOK。

この辺りは Auto-Layout, Constrains というキーワード辺りの話しになりますがまだまだ勉強が必要そうです。