这是我想重构的代码:
let myCell = MyCustomTableViewCell()
self.createCell(myCell, reuseIdentifierString: "myCellIdentifier")
MyCustomTableViewCell 符合 SetCell 协议(protocol),因此可以正常工作。并且 SetCell 协议(protocol)不是 @obj_c 协议(protocol)。这是一个快速的协议(protocol)
private func createCell<T where T:SetCell>(classType: T, reuseIdentifierString: String) -> UITableViewCell {
var cell = _tableView.dequeueReusableCellWithIdentifier(reuseIdentifierString) as T
cell.setText()
return cell.getCustomCell()
}
现在我重构了我的代码,我想根据一个字符串创建 myCell,但该字符串与我的类名完全相同。我不想使用 else-if 或 switch-case
let myCell: AnyClass! = NSClassFromString("MyCustomTableViewCell")
self.createCell(myCell, reuseIdentifierString: "myCellIdentifier")
但是现在 AnyClass 的 myCell 不符合协议(protocol)。 我该怎么做?
最佳答案
您需要的代码比这多一点。您将获得 AnyClass 而不是 AnyObject。因此,您需要创建该类型的实例。你可以试试这个:
let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var theObject: NSObject! = objectType() as NSObject
var myCell:MyCell = theObject as MyCell
为了让它符合您的协议(protocol),您可以尝试一些事情:
<强>1。您可以为所有符合协议(protocol)的单元格创建一个基类。并在上面的代码中使用它而不是 UITableViewCell。为此,您可以使用如下代码:
protocol SetCell {
func setcell() {}
}
class BaseUITableViewCell : UITableViewCell, SetCell {
func setcell() {}
}
class MyCell : BaseUITableViewCell {
override func setcell() {}
}
let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var theObject: NSObject! = objectType() as NSObject
var myCell:BaseUITableViewCell = theObject as BaseUITableViewCell
<强>2。您可以使用您的扩展来扩展 UITableViewCell,例如添加一个空扩展
extension UITableViewCell: SetCell {}
//编译时错误:
Declarations from extensions cannot be overridden yet
//Edwin:奇怪,这在文档中。所以看起来这个已经过时了......
<强>3。您可以定义一个符合如下协议(protocol)的变量:
@objc protocol SetCell {
func setcell() {}
}
let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var myCell2:protocol<SetCell> = objectType() as protocol<SetCell>
关于ios - 如何根据 Swift 中的字符串创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25728282/