2014年7月11日金曜日

SwiftコードだけでUITableViewを配置

Storyboardを使わずに、Swiftコードだけで
UIViewController に UITableView を配置する例

( UITableView を配置する母体となる UIViewController は
Storyboard上に存在している前提です )


import UIKit

class HogeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView : UITableView = UITableView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        tableView.frame = CGRectMake(0, 45, self.view.bounds.size.width, 1000)
        self.view.addSubview(tableView)
        
        tableView.delegate = 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 1
    }
    
    // セルの設定
    func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
        cell.textLabel.text = "セル \(indexPath.row)番目"
        cell.detailTextLabel.text = "詳細"
        return cell;
    }
    
    // セルが選択されたときに呼ばれる
    func tableView(tableView: UITableView?, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
        println("選択された \(indexPath.row)番目")
    }

}

動作確認環境
Xcode6beta3

0 件のコメント:

コメントを投稿