ios - 为什么 Xcode 自动修复会创建两个同名的方法 `func tableView`?
问题描述
我是 swift 编程语言的新手。我已经看到,在 Swift 中创建表时,您必须在 ViewController 类中实现两个方法,扩展UITableViewDelegate
, UITableViewDataSource
。我不明白的是,为什么 Xcode 的自动修复会在这个类中创建两个同名的方法func tableView
?
这不会造成方法重载或导致错误吗?
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
let dataArray = ["firt", "second", "third", "four", "five", "six"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let videoCell = tableView.dequeueReusableCell(withIdentifier: "video title", for: indexPath)
return videoCell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.dataSource = self
}
}
解决方案
即使它们具有相同的函数名称tableView
它们是非常不同的功能。它们都符合 UITableView 委托,并且基于其协议方法将影响 tableView 的不同功能。
didSelectRowAt
不一样
cellForRowAt
仅当您明显选择了一个单元格时才会触发是否选择行
行的单元格被认为是“主”tableView 函数,因为此函数填充您的 tableView 数据单元格。
--EDIT 基于下面的 Duncan C 评论。
“您的示例函数的名称不是 tableView,函数的名称是 tableView(_:cellForRowAt:) (参数实际上是函数名称的一部分,或者更确切地说是函数“签名”。)“
这是描述答案的绝佳方式。
编辑2----
此外,这在 swift 编程中很常见。最直接的例子是collectionView
. 它使用几乎相同的命名约定。
cellForRowAt
和
didSelectRowAt
您将遇到许多其他委托方法,这些方法与您在问题中描述的情况相同。
推荐阅读
- r - 基于 numericInput() 创建具有最大选择数的 selectInput()
- c# - 通过三种表格制作计算器——如何正确连接表格,怎么做?
- logstash - 如何设置/更改 Logstash 的 @version 字段?
- html - 如何从左到右创建动画或制作淡入淡出Angular 4
- php - 无法安装 FOSUserBundle
- sql-server - 如何连接两个事实表?
- c++ - 为什么当我尝试将所有字符串转移到我的自定义队列模板并尝试打印时,它只打印队列中的最后一个?
- neo4j - 根据条件创建节点
- php - 任意顺序的 PHP 搜索查询
- android - OutputStream 空对象错误