許多時候我們都有在普通的繼承自 UIViewController 的控制器中使用 TableView 的需求衡怀,這時候就需要當(dāng)前控制器類繼承 UITableViewDelegate 和 UITableViewDataSource,然后再初始化:
@IBOutlet weak var firstTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
firstTableView.delegate = self
firstTableView.dataSource = self
}
這時候,firstTableView.dataSource = self 這一行會報錯:
Type 'SomeViewController' does not confirm to protocol 'UITableViewDataSource'
解決方案如下:
在該類中新增如下方法:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCenter", forIndexPath: indexPath) as UITableViewCell
cell.textLabel.text = indexPath.row.description
return cell
}