我是Swift和iOS開發的新手,我嘗試以編程方式實現UITableView,而不使用xib或Storyboard。這是我的代碼:以編程方式在Swift中創建UITableView
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let table: UITableViewController = MyTableViewController()
let tableView: UITableView = UITableView()
tableView.frame = CGRect(x: 10, y: 10, width: 100, height: 500)
tableView.dataSource = table
tableView.delegate = table
self.view.addSubview(tableView)
}
}
MyTableViewController.swift
import UIKit
class MyTableViewController: UITableViewController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
NSLog("sections")
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
NSLog("rows")
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
NSLog("get cell")
let cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
cell.textLabel!.text = "foo"
return cell
}
}
但是當我運行的應用程序,我得到的是空表。在日誌中我看到幾行sections
和rows
,但沒有get cell
。我該如何解決這個代碼以獲得6行foo
文本的表格?
爲什麼你有一個'ViewController'與它自己的表視圖和一個'MyTableViewController',它也有它自己的表視圖? – rmaddy
''ViewTidLoad'後發佈'MyTableViewController'。所以請儘量保留一個參考。 –
如果您是iOS和Swift的新手,我強烈建議您在網絡或iTunesU上查看教程。關於iTunesU的斯坦福大學課程叫做「用Swift開發iOS 9應用程序」將解釋關於對象圖以及如何使用iOS框架。 –