【发布时间】:2016-01-02 11:51:44
【问题描述】:
我正在学习 swift 2.0,我想知道您是否还需要像在 Obj-C 中一样添加代码 tableView.datasource = self 和 tableView.delegate = self 以符合协议?
示例代码:
class AboutViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
// conform to protocols
aboutTableView.dataSource = self
aboutTableView.delegate = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 2
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 50
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
// Code here
}
}
现在表格视图会在每个单元格中加载正确的数据。
但是,如果我从 viewDidLoad 中删除 aboutTableView.datasource = self 和 aboutTableView.delegate = self,我的表格视图是空白的。这是为什么呢?
是否仍然需要此代码,因为我在 swift 中看到许多不再包含此代码的 youtube 教程,我很困惑为什么我的代码没有它就无法工作?
【问题讨论】:
-
这与语言无关。 – 但请注意,如果您有 UIViewController 或 UITableViewController 子类,情况会略有不同。后者已经给自己设置好了它的tableView的delegate和数据源。
-
在功能上,Swift 的行为与 ObjectiveC 没有什么不同。 Swift 的强大来自于语言的特性。
标签: ios swift uitableview