tableView: cellForRowAtIndexPath:方法中有兩個(gè)獲得重用cell的方法
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
和
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]
請(qǐng)問(wèn)他們有什么區(qū)別低矮?
當(dāng)我用 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]的時(shí)候?yàn)槭裁纯倛?bào)錯(cuò)
reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
------解決方案--------------------------------------------------------
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier;
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
NS_AVAILABLE_IOS(6_0); // newer
區(qū)別在這兒
------解決方案--------------------------------------------------------
1 這個(gè)方法在SDK5.0是運(yùn)行不起來(lái)的军掂。
2 如果需要使用這個(gè)方法良姆,你必須使用配套的方法來(lái)一起用幔戏,下面兩個(gè)配套方法:
// Beginning in iOS 6, clients can register a nib or class for each cell.
// If all reuse identifiers are registered, use the newer -dequeueReusableCellWithIdentifier:forIndexPath: to guarantee that a cell instance is returned.
// Instances returned from the new dequeue method will also be properly sized when they are returned.
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);
- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);
注意看上面的注釋
3 比如你已經(jīng)用NIB做了一個(gè)Cell痊剖,或者自定義了一個(gè)Cell垒玲。我們?cè)谀銊?chuàng)建UITableView的時(shí)候,就可以順帶
self.tableView.backgroundColor = xxxx;
[self.tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];
這樣你在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath這個(gè)方法里叮贩,你就可以省下這些代碼:
static NSString *CellIdentifier = @"Cell";
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//設(shè)置你的cell
}
而只需要
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
如果使用 [self.tableView registerClass:[tableViewCell class] forCellReuseIdentifier:@"CustomCell"];注冊(cè),cell的樣式為默認(rèn)樣式,
采用注冊(cè)的方式,在
<span style="color:#333333;">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath</span>
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" ];
就實(shí)現(xiàn)了cell 的重用;
或者不注冊(cè),直接在
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"diyigdgdfg" ];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"diyigdgdfg"];
}
也可實(shí)現(xiàn)cell 的重用