我正在使用仿制功能来改善tableView细胞,如下所示;
public func registerNib<T: UITableViewCell>(_:T.Type) {
print("Registering.....")
print(T.self)
let nib = UINib(nibName: String(describing: T.self), bundle: nil)
register(nib, forCellReuseIdentifier: String(describing: T.self))
}我写了两个函数来注册细胞,一个是单细胞,另一个是多个细胞。
//单细胞登记册
func setup<T: UITableViewCell>(cell:T.Type) {
print(cell)
tableView.registerNib(cell)
self.setupParameters(.....)
}//多单元寄存器
func setup<T: UITableViewCell>(cells:[T.Type]) {
for cell in cells {
print(cell)
tableView.registerNib(cell)
}
self.setupParameters(.....)
}对于单细胞实现,您可以按下面的方式调用func,它将正确地执行registerNib。
self.baseTableView.setup(cell: CompetencyCell.self, rowHeight: 60)
**************
Output:
CompetencyCell
Registering...
CompetencyCell但是,在多个实施过程中也会出现问题;
self.baseTableView.setup(cells: [CompetencyCell.self, BehaviorCell.self], rowHeight: 60)
**************
Output:
CompetencyCell
BehaviorCell
Registering...
UITableViewCell
UITableViewCell我真的想知道是什么原因,还是我错过了什么?它看起来是相同的行为,但是当我想将T.Type值传递给RegisterNib方法时,它会转到UITableViewCell,当然,过了一段时间,我就崩溃了,因为它找不到单元格。
你有什么建议吗?非常感谢。
发布于 2018-09-13 12:52:05
调用泛型函数时,泛型类型T表示单个静态类型。
[T.Type]是荒谬的,因为它声明了相同的类型说明符的数组。
T并不意味着Any!
发布于 2018-09-13 13:14:53
正如在vadian的答案中所描述的,泛型不是一个很好的工具,用于包含多种类型值的Array。
你可以试试这样的东西:
extension UITableView {
public func registerNib(_ type: UITableViewCell.Type) {
print("Registering.....")
print(type)
let nib = UINib(nibName: String(describing: type), bundle: nil)
register(nib, forCellReuseIdentifier: String(describing: type))
}
}这是:
func setup(cells: [UITableViewCell.Type] /*, otherParams: ...*/) {
for cell in cells {
print(cell)
tableView.registerNib(cell)
}
//self.setupParameters(.....)
}https://stackoverflow.com/questions/52314012
复制相似问题