我嘗試爲UITableView
和UICollectionView
創建一些通用擴展來減少處理集合所需的鍋爐代碼。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
,因爲它會在內部斷言時失敗。我試圖玩嘗試抓住機制在斯威夫特但無濟於事。
有什麼建議嗎?
我知道我只能在VC註冊筆尖,但這不是擁有這些類別的要點。
如果您在一個'UICollectionView'中使用多個單元格類型,就不夠好。需要存儲啞數組,必須有更簡潔的方式來做到這一點。 – Krodak