首页 > 解决方案 > 为什么 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
    }

}

标签: iosswiftuitableview

解决方案


即使它们具有相同的函数名称tableView

它们是非常不同的功能。它们都符合 UITableView 委托,并且基于其协议方法将影响 tableView 的不同功能。

didSelectRowAt

不一样

cellForRowAt
  • 仅当您明显选择了一个单元格时才会触发是否选择行

  • 行的单元格被认为是“主”tableView 函数,因为此函数填充您的 tableView 数据单元格。

--EDIT 基于下面的 Duncan C 评论。

“您的示例函数的名称不是 tableView,函数的名称是 tableView(_:cellForRowAt:) (参数实际上是函数名称的一部分,或者更确切地说是函数“签名”。)“

这是描述答案的绝佳方式。

编辑2----

此外,这在 swift 编程中很常见。最直接的例子是collectionView. 它使用几乎相同的命名约定。

cellForRowAt

didSelectRowAt

您将遇到许多其他委托方法,这些方法与您在问题中描述的情况相同。


推荐阅读