標籤:
今天在學習IAP的時候無意間看到原來 tableView: cellForRowAtIndexPath:方法中有兩個獲得重用cell的方法 ,一直以來都是用UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];那下面的這個怎麼用呢,感覺比較怪,假設沒有重用的豈不是為空白了UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]具體有什麼區別呢,並且當我用 UITableViewCell *cell = [tableView dequeueReusableCellWithI dentifier:CellIdentifier forIndexPath:indexPath]的時候,為什麼總報錯
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‘,經過查閱,知道原來此方法為6.0新加的,在SDK5.0是運行不起來的。 如果需要使用這個方法,你必須使用配套的方法來一起用,下面兩個配套方法選其一:
- (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 比如你已經用NIB做了一個Cell,或者自訂了一個Cell。我們在你建立UITableView的時候,就可以順帶
self.tableView.backgroundColor = xxxx;
[self.tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];
這樣你在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath這個方法裡,你就可以省下這些代碼:
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
//設定你的cell
}
而只需要
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
//設定你的cell
整體來說6.0卻是比5.0更省勁
重用cell的兩種方法