【问题标题】:Swift 3: Understand syntax change for UITableViewDataSource methodSwift 3:了解 UITableViewDataSource 方法的语法变化
【发布时间】:2017-01-23 23:42:04
【问题描述】:

我对 Swift 3 函数调用有一些疑问。下面是一个例子。

老斯威夫特:

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell

斯威夫特 3:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

上面的语法很好。但现在 Xcode 向我显示一个错误并要求我执行以下操作:

@objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

我不明白为什么我必须声明@objc(tableView:cellForRowAtIndexPath:)

仅当我尝试在扩展下实现表视图数据源方法时才会发生这种情况。 numberOfRowsInSectionviewForHeaderInSection 也不会发生这种情况。

谁能帮我理解为什么会这样?

【问题讨论】:

    标签: ios uitableview swift3


    【解决方案1】:

    如果你在 Objective c 中使用这个函数,Swift 编译器会强制在函数之前编写 Objc(funcName)。根据应用程序文档

    使用@objc(name) 属性为以下对象提供 Objective-C 名称 必要时的属性和方法。例如,您可以标记一个 名为 enabled 的属性有一个名为 isEnabled 的 getter 像这样的Objective-C:

        var enabled: Bool {
        @objc(isEnabled) get {
            // ...
          }
       }
    
    • 要避免这种情况,请使用扩展来编写 TableView 数据源和委托
     extension YourViewControllerName:UITableViewDataSource, UITableViewDelegate {
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
        {
            return 10
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    
            let cell = tableView.dequeueReusableCell() as SplitAddContactCell
            return cell
        }
    
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 80.0
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      虽然我不确定是什么触发了@objc,但我可以建议以下方法:

      将 tableView 变量存储在 viewDidLoad 中的某处:

      let tv = tableView!
      

      然后将鼠标悬停在 tableView 变量上并按下命令按钮并单击。

      这应该带您进入 UITableView 的界面

      然后,将鼠标悬停在 UITableViewDelegate 或 UITableViewDataSource 上,同时按下命令按钮并单击。

      现在您可以看到新的签名。

      很多东西都变了...升级愉快!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多