代码之家  ›  专栏  ›  技术社区  ›  Leo

Swift 3 UITableViewDataSource选择器

  •  2
  • Leo  · 技术社区  · 9 年前

    更新到Swift 3后,我在以下代码中遇到错误:

    extension MyViewController: UITableViewDataSource {
        //...
    
        func tableView(_ tableView: UITableView, 
                       heightForRowAt indexPath: IndexPath) -> CGFloat {
            return someValue
        }
    }
    

    Objective-C方法“tableView:heightForRowAt:”由方法提供 “tableView(_:heightForRowAt:)”与要求不匹配 选择器('tableView:heightForRowAtIndexPath:')

    它可以用

    @objc(tableView:heightForRowAtIndexPath:)
    func tableView(_ tableView: UITableView,
                   heightForRowAt indexPath: IndexPath) -> CGFloat {
        return someValue
    }
    

    谁能解释新版Swift中签名更改的动机?中没有信息 migration guide

    1 回复  |  直到 9 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

    随着 斯威夫特3.0 为了可读性,库中许多方法的签名都已更改(请参见 API Design Guidelines ).

    例如,将您引用的方法的当前签名与其在代码完成建议列表中的表示进行比较 X代码 :

    // implementation:
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {...}
    
    // code completion:
    tableView(tableView: UITableView, heightForRowAt: IndexPath)
    

    与此相反,以前的实现用于显示冗余信息:

    // implementation:
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {...}
    
    // code completion:
    tableView(tableView: UITableView, heightForRowAtIndexPath: NSIndexPath)
                                                    ---------  -----------
    

    此外,函数或方法的实现现在需要下划线( _ )甚至为第一个参数设置,以便在调用函数/方法时忽略参数标签(请参见: https://stackoverflow.com/a/38192263/6793476 ).

    显然,库中的一些选择器尚未更新,因此您需要提供正确的(“旧”)选择器名称(请参见: https://stackoverflow.com/a/39416386/6793476 以及有关选择器的详细信息: https://stackoverflow.com/a/24007718/6793476 ).

    我希望这能有所帮助。