"まだ"の力 [Swift]基礎辞書

学んだことを書いていきます。質問やエラーなどございましたらお気軽にコメントお願いします。

「UITableView」

UITableViewこれをマスターすると作れるアプリの幅がかなり広がると噂です。


006 UITableViewでテーブルを表示 - Swift Docs

サイトを参考にしつつ時自分なりの解釈を補足していきます。




import UIKit
        
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
            
    // Tableで使用する配列
    let Items: NSArray = ["戦士", "魔法使い", "モンク"]
    var statusTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
                
                
        // Viewの高さと幅を取得する.
        let Width: CGFloat = UIScreen.mainScreen().bounds.size.width  //UIScreenの記事で詳しく取り上げてます
        let Height: CGFloat = UIScreen.mainScreen().bounds.size.height
                
        // TableViewの作成
        statusTableView = UITableView(frame: CGRect(x: 0, y: 50, width: Width, height: Height - 50))
                
        // Cell名の登録(後に使い回しをするため)
        statusTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "statusCell")
                
        // DataSourceを自分のクラスに設定(デリゲートについては過去記事にて詳しく取り上げております)
        statusTableView.dataSource = self
        
        // Delegateを自分のクラスに設定
        statusTableView.delegate = self
                
        // Viewに追加
        self.view.addSubview(statusTableView)
    }
    
    /*
    Cellの総数を返すデータソースメソッド.
    (実装必須)
    */
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Items.count
    }
            
    /*
    Cellに値を設定するデータソースメソッド.
    (実装必須)
    */
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
                
        // 再利用するCellを取得する.
        let cell = tableView.dequeueReusableCellWithIdentifier("statusCell", forIndexPath: indexPath)
        
        // Cellに値を設定する.
        cell.textLabel!.text = "\(Items[indexPath.row])"
        
        return cell
    }
}

f:id:kichie_com:20151225173756p:plain
完成です!

他のデータソースメソッドによって様々な機能を追加できるので興味ある方はまだまだ調べてみるといいと思います。