tableView再常見(jiàn)不過(guò)了博个,現(xiàn)在的項(xiàng)目中基本上都會(huì)用到很多tableView迅细。并且很多時(shí)候tableView上每一行的內(nèi)容都不同喜庞。
如果你有這樣的需求:
一個(gè)展現(xiàn)用戶信息的頁(yè)面株搔,有的cell最右側(cè)是圖片筑辨,有的cell最右側(cè)顯示的是文本(名字总滩、手機(jī)號(hào)纲堵、性別、余額)
Or:
一個(gè)填寫用戶信息的列表闰渔,有各種各樣的textField
上述的兩種頁(yè)面有兩個(gè)共同的特點(diǎn):
tableViewCell的數(shù)量有限席函,并且數(shù)量不大。不需要重用cell也能搞定冈涧。
比起寫出多個(gè)cell子類去適應(yīng)這些情況茂附,不如把這些label或者textfield作為viewControler的熟悉,在tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)代理方法中把這些特定控件加到cell上炕舵,修改或者獲取這些控件時(shí)非常方便何之。
然而這個(gè)時(shí)候tableView的cell重用機(jī)制就非常棘手:
注冊(cè)多種cell很麻煩,在這種情況下很多余咽筋。
很多人應(yīng)該遇到過(guò)的情況溶推,重用cell會(huì)讓視圖變得很混亂,一些圖片或空間因?yàn)橹赜玫某霈F(xiàn)在了不該出現(xiàn)的地方
在storyBoard中可以設(shè)置static cell奸攻,來(lái)關(guān)閉重用蒜危。可是如果tableView是用代碼建立的睹耐,就沒(méi)有某個(gè)系統(tǒng)庫(kù)的方法能夠設(shè)置static cell辐赞。
于是在swift下我寫了一個(gè)簡(jiǎn)單的extension可以實(shí)現(xiàn)關(guān)閉重用的效果。實(shí)現(xiàn)原理也非常簡(jiǎn)單硝训,show code:
extension UITableView {
/*
彈出一個(gè)靜態(tài)的cell响委,無(wú)須注冊(cè)重用,例如:
let cell: GrayLineTableViewCell = tableView.mm_dequeueStaticCell(indexPath)
即可返回一個(gè)類型為GrayLineTableViewCell的對(duì)象
- parameter indexPath: cell對(duì)應(yīng)的indexPath
- returns: 該indexPath對(duì)應(yīng)的cell
*/
func mm_dequeueStaticCell<T: UITableViewCell>(indexPath: NSIndexPath) -> T {
let reuseIdentifier = "staticCellReuseIdentifier - \(indexPath.description)"
if let cell = self.dequeueReusableCellWithIdentifier(reuseIdentifier) as? T {
return cell
}else {
let cell = T(style: .Default, reuseIdentifier: reuseIdentifier)
return cell
}
}
}
無(wú)須注冊(cè)窖梁。
將cell直接聲明為其需要的類型赘风,改方法會(huì)自動(dòng)返回這個(gè)類型的cell。
最后:
泛型函數(shù)的調(diào)用必須是以下寫法:
let cell: GrayLineTableViewCell = tableView.mm_dequeueStaticCell(indexPath)
如果寫成:
let cell = tableView.mm_dequeueStaticCell<GrayLineTableViewCell>(indexPath)
將會(huì)報(bào)錯(cuò)纵刘,這種寫法只適用于 泛型類型邀窃,不適用于 泛型函數(shù)