swiftの基礎まとめシリーズ。
アプリ作成には避けて通れないTableViewの使い方です。
環境
- Xcode Version 6.1 (6A1052d)
tableviewの実装
前回と同じように、storyboardを使わない実装方法です。
といってもobjective-c版とほとんど変化はありません。
import UIKit class TestsViewController: UITableViewController { // tableviewで表示する配列 var tests = [Test]() // testdata load func test() { // Do any additional setup after loading the view, typically from a nib. // self.navigationItem.leftBarButtonItem = self.editButtonItem() //let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") //self.navigationItem.rightBarButtonItem = addButton if tests.isEmpty { println("empty"); } else { println("not empty"); } var obj = Test(id: 1, testCode: "001", testName: "英語", imagePath: "asasa") tests.append(obj) var obj2 = Test(id: 2, testCode: "002", testName: "数学", imagePath: "asasa") tests.append(obj2) if tests.isEmpty { println("empty"); } else { println(tests.count); } } override func viewDidLoad() { super.viewDidLoad() self.test() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier:"testcell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tests.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier:"testcell") let test = tests[indexPath.row] as Country cell.textLabel.text = test.testName return cell; } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let test = tests[indexPath.row] let resultViewController = ResultViewController() navigationController!.pushViewController(resultViewController, animated: true) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { //objects.removeObjectAtIndex(indexPath.row) //tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
objective-cのテーブルviewより随分とスッキリした短いコードになっています。
一番のポイントは
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier:"testcell")
です。
storyboardを使わない場合は、表示に利用するcellをviewDidLoadメソッドで登録しておく必要があります。カスタムセルを利用する場合も同様です。
0 件のコメント:
コメントを投稿