我尝试为 UITableView
和 UICollectionView
创建一些通用扩展,以减少处理集合所需的锅炉代码。
对于 UITableView
我有这个:
extension UITableView {
public func dequeueReusableCell<T:UITableViewCell>(type: T.Type) -> T {
let tableCell : T
let cellIdentifier = String(T)
if let cell = self.dequeueReusableCellWithIdentifier(cellIdentifier) as? T {
tableCell = cell
} else if let _ = NSBundle(forClass: T.classForCoder()).pathForResource(cellIdentifier, ofType:"nib") {
self.registerNib(UINib(nibName: cellIdentifier, bundle: nil), forCellReuseIdentifier: cellIdentifier)
if let cell = NSBundle(forClass: T.classForCoder()).loadNibNamed(cellIdentifier, owner: nil, options: nil)[0] as? T {
tableCell = cell
} else {
//if anyone had better suggestion for fallback, you're welcome to comment
tableCell = T(style: .Default, reuseIdentifier: cellIdentifier)
}
} else {
tableCell = T(style: .Default, reuseIdentifier: cellIdentifier)
}
return tableCell
}
}
对于 UICollectionView
目前我只有这个:
extension UICollectionView {
public func dequeueReusableCell<T:UICollectionViewCell>(type: T.Type, indexPath: NSIndexPath) -> T {
let collectionCell : T
let cellIdentifier = String(T)
if let _ = NSBundle(forClass: T.classForCoder()).pathForResource(cellIdentifier, ofType:"nib") {
self.registerNib(UINib(nibName: cellIdentifier, bundle: nil), forCellWithReuseIdentifier: cellIdentifier)
collectionCell = self.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! T
}
else {
collectionCell = T()
}
return collectionCell
}
}
这行得通,但我认为它不够整洁。我想改进的是只调用一次 registerNib
。不幸的是,我无法调用 dequeueReusableCellWithReuseIdentifier
,因为它会在内部断言时失败。我试过在 Swift 中使用 try catch 机制,但无济于事。
有什么建议吗?
我知道我可以在 VC 中注册一次 nib,但这并不是拥有这些类别的意义。
最佳答案
这是您可以使用的示例代码。这个想法是传递一个已经注册的 nib 名称数组,每当您注册 xib 时就会填充这些名称。你可以在你的代码中使用它,从你调用的地方你只需要传递一个数组。这可能是一个全局数组。
您只需在传递单元 ID 名称和全局数组的函数开头调用它。
extension ViewController
{
func registerNibName(name:String, inout alreadyRegistered:[String])
{
if !alreadyRegistered.contains(name) {
alreadyRegistered.append(name)
//self.registerNib(name)
print("registerNib with name \(name)")
}
}
}
关于ios - UICollectionView - 仅在需要时注册 Nib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35146821/