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];
這樣就夠了,這下你明白了嗎?
轉(zhuǎn)載自:? http://www.zpluz.com/thread-3504-1-1.html