gpt4 book ai didi

ios - 想在 Swift 中重新定义 willDisplayCell 方法。如何重新定义类方法

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

我在自定义单元格类中使用某些 UI 组件,我想在 willDisplayCell 方法中配置这些组件。原来的定义是

public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)

现在使用 cell.myTextField.text = "customise"给出单元格没有任何组件作为 myTextField 的错误

为了解决这个问题,我必须重新定义方法

public func tableView(tableView: UITableView, willDisplayCell cell: **myCustomCellClass**, forRowAtIndexPath indexPath: NSIndexPath)

任何有关如何执行此操作以及随后如何在 swift 中重新定义任何现有类方法的线索都会很棒。提前致谢。

最佳答案

不幸的是,您不能更改参数类型,因为那样会更改接口(interface)。您可以将方法的返回类型更改为子类型,但不能将方法参数更改为子类型。

你真的有一个选择,动态转换:

public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// use as? or as! to cast UITableViewCell to your desired type
}

当然,你可以通过多种方式实现同​​样的效果,例如,你可以创建一个重定向方法:

public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
self.tableView(tableView, willDisplayMyCell: cell as! MyCellClass, forRowAtIndexPath: indexPath)
}

private func tableView(tableView: UITableView, willDisplayMyCell myCell: MyCellClass, forRowAtIndexPath indexPath: NSIndexPath) {
// do something
}

您可以将其抽象为 UITableViewDelegate 的子协议(protocol):

class MyTableViewCell : UITableViewCell {

}

protocol MyTableViewDelegate : UITableViewDelegate {
associatedtype CellClass: UITableViewCell

func tableView(
tableView: UITableView,
willDisplayMyCell cell: CellClass,
forRowAtIndexPath indexPath: NSIndexPath)
}

extension MyTableViewDelegate {
func tableView(
tableView: UITableView,
willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) {

self.tableView(tableView, willDisplayMyCell: cell as! CellClass, forRowAtIndexPath: indexPath)
}
}

这很酷的一点是协议(protocol)是可重用的,然而,这一切都归结为 as?as! 动态转换。

关于ios - 想在 Swift 中重新定义 willDisplayCell 方法。如何重新定义类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37653159/

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