gpt4 book ai didi

ios - 符合 Swift 中的 UITableViewDelegate 和 UITableViewDatasource 吗?

转载 作者:搜寻专家 更新时间:2023-11-01 05:53:45 25 4
gpt4 key购买 nike

我正在学习 swift 2.0,我想知道您是否还需要添加代码 tableView.datasource = selftableView.delegate = self 就像在 Obj- C 符合协议(protocol)?

示例代码:

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
}
}

现在表格 View 在每个单元格中加载正确的数据。

但是,如果我从 viewDidLoad 中删除 aboutTableView.datasource = selfaboutTableView.delegate = self,我的 TableView 是空白的。这是为什么?

是否仍然需要此代码,因为我看到许多 YouTube 教程不再包含此代码,而且我很困惑为什么没有它我的代码就不能工作?

最佳答案

首先,那就是完全独立于哪种语言你使用 Swift 或 Objective-C。

但是有两种不同的情况可能会引起混淆:

UITableViewController 子类:

UITableViewController 已经符合 UITableViewDataSourceUITableViewDelegate。它有一个 tableView 属性,其 dataSourcedelegate 属性已设置为 self

在您的子类中,您通常覆盖数据源和委托(delegate)方法。

具有 UITableView 属性的 UIViewController 子类:

在这里,您在子类中定义了一个 UITableView 属性并在您的代码中对其进行初始化,或者将其连接到界面构建器中的 TableView 。

在这种情况下,您必须设置 dataSourcedelegatetableview 的属性,在代码中或在界面中生成器,如 luk2302's answer 中所述。

如果数据源和委托(delegate)是 View Controller 本身,那么你必须明确声明协议(protocol)一致性,并实现数据源和委托(delegate)方法(但没有覆盖父类(super class)方法)。


当然,在这两种情况下, TableView 数据源和委托(delegate)可以设置为一个不同的对象,它不一定是 View Controller 本身。

关于ios - 符合 Swift 中的 UITableViewDelegate 和 UITableViewDatasource 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34565570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com