【发布时间】:2017-09-30 11:02:09
【问题描述】:
我尝试对 cellIdentifier 使用类型和枚举而不是字符串
我不想使用单元格类名作为标识符,因为我可以为一种类型的单元格设置多个标识符(例如不同表格视图中的基本单元格)
enum TableViewCellIdentifier: String {
case formCell, questionCell
// Here I can have the type, and I want to use it to ensure the cell dequeued by the identifier is the right type
var typeCell: UITableViewCell.Type {
switch self {
case .formCell:
return UITableViewCell.self
case .questionCell:
return QuestionCell.self
}
}
// I could use an extension of UITableView to build an other version of dequeueCell,
// but I'll choose after it the type constraint will let me choose.
// Here I want to constraint the return type with the value of myValue.typeCell
func dequeueCell(with tableView: UITableView, for indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: self.rawValue, for: indexPath)
}
// func dequeueCell<T: self.typeCell>(with tableView: UITableView, for indexPath: IndexPath) -> T {
// return tableView.dequeueReusableCell(withIdentifier: self.rawValue, for: indexPath) as! T
// }
}
有什么想法吗?
谢谢!
【问题讨论】:
-
为什么不同的表需要不同的标识符?您可以随时检查您在委托函数上出列哪个表,
if tableView === self.firstTableView ... -
例如,我可以有一个名为
formCell的单元格类 UITableViewCell 并在另一个视图控制器类 UITableViewCell 中有另一个单元格名为answerCell。我还可以有一个名为questionCell的单元格类 QuestionCell。我认为将我的 formCell 和 answerCell 命名为相同的标识符并不是一件好事
标签: ios swift uitableview generics reuseidentifier