我正在尝试将单元格转换为动态类类型:
struct Item {
var cellClass: AnyClass
}
let cellClass = item.cellClass
let cell: cellClass = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
但是,我收到错误:
cellClass 不是类型
执行此操作的正确方法是什么?
最佳答案
AnyClass
定义为 AnyObject.Type
,并且您无法创建 AnyObject
类型的实例,它没有公共(public)初始值设定项。 ..
但是,如果您知道所有单元格都将是 UITableViewCell
的子类型,则可以使用以下命令执行您想要的操作:
struct Item {
var cellClass: UITableViewCell.Type
}
class Test: UITableViewCell {
var str = ""
}
// create an instance of Item with the class Test
let i = Item(cellClass: Test.self)
// then create an instance of Test by using the instance of Item
var t = i.cellClass.init()
然后,当你询问if t is Test
时,它会说true
。
关于Swift 将变量转换为变量类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33923804/