首页 > 解决方案 > 自定义表格视图单元格为字符串

问题描述

我正在将我的应用程序从 Swift 2 更新到 Swift 4,并且在通过以下方式将 UITableViewCell 转换为 String 时似乎丢失了一些功能:

String(MyTableViewCell)

我尝试使用它的实例是:

let cell = tableView.dequeueReusableCell(withIdentifier:String(PlayerReportCell), forIndexPath: indexPath) as! PlayerReportCell

这只是失去了功能还是有新的方法?

我得到的错误是..

Cannot invoke initializer for type 'String' with an argument list of type '((PlayerReportCell).Type)'

标签: iosswiftuitableview

解决方案


我不记得以前能做到这一点,但在 Swift 4.2 中,你可以这样做:

 "\(PlayerReportCell.self)"

它基本上是使用字符串插值来插入类型的元类型对象。

或者,使用String(describing:)

String(describing: PlayerReportCell.self)

请注意,这依赖于实现细节,并且可能会在未来的 swift 版本中中断,就像您的旧代码一样。最好将标识符硬编码进去。


推荐阅读