-
重用機(jī)制
重用機(jī)制實(shí)現(xiàn)了數(shù)據(jù)和顯示的分離,并不為每個數(shù)據(jù)創(chuàng)建一個UITableViewCell,只創(chuàng)建屏幕可顯示的最大的cell個數(shù)+1(這個“1”是uitableview第一次滑動第一個cell進(jìn)入reusableTableCells過程中出現(xiàn)的),然后去循環(huán)重復(fù)使用這些cell,既節(jié)省空間,又達(dá)到需要顯示的效果.
重用機(jī)制主要用到了一個可變數(shù)組(NSMutableArray* visiableCells)和一個可變的字典(NSMutableDictnery* reusableTableCells)。visiableCells,用來保存屏幕顯示的cell。reusableTableCells,用來保存可重復(fù)利用的cell.(之所以用字典是因?yàn)榭芍赜玫腸ell有不止一種樣式,我們需要根據(jù)它的reuseIdentifier,也就是所謂的重用標(biāo)示符來查找是否有可重用的該樣式的cell). -
UITableView重用的幾種寫法
1、免注冊方式
static NSString *cellID = @"cell";
//根據(jù)identifier在緩存的字典中找是否有已經(jīng)初始化好的cell,如果沒有就新建
UITableView *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [[HORTransitReportCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellID];
}
return cell;
2、注冊方式
2.1、現(xiàn)在viewDidLoad進(jìn)行cell注冊
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier: identifier];
2.2、cellForRowAtIndexPath 創(chuàng)建
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 從重用隊(duì)列中取cell 由于viewDidLoad中已經(jīng)注冊過cell,系統(tǒng)會自動做判斷,不用再次手動判斷單元格是否存在
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: identifier forIndexPath:indexPath] ;
return cell ;
}
-
自定義cell,且cell高度可變
因?yàn)閏ell高度隨機(jī),所以應(yīng)保證identifer也是單一的,不去進(jìn)行復(fù)用,保證每一個cell有唯一的identifer。
static NSString *cellID = [NSString format@"cell%ld%ld",indexPath.section,indexPath.row];
//根據(jù)identify在緩存的字典中找是否有已經(jīng)初始化好的cell
UITableView *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [[HORTransitReportCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellID];
}
return cell;
-
UITableviewCell注冊和不注冊兩種情況獲取cell的的用法
1、免注冊方法
- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;
// Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
(返回給代理一個已經(jīng)分配的cell,代替一個新的cell,如果沒有已分配的cell,則返回nil,使用這個方法就不需要注冊了)
2、注冊方法
- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);
// newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered
如果cell的identifier是注冊過的,那么這個新列出的方法保證返回一個cell (有分配的就返回已分配的cell,沒有返回新的cell)并適當(dāng)調(diào)整大小,可省略cell空值判斷步驟,用這個方法cell必須注冊,不是自定義的cell,UITableViewCell也要注冊