UITableView的registerClass forCellReuseIdentifier用法詳解

轉載自:  http://www.zpluz.com/thread-3504-1-1.html

tableView: cellForRowAtIndexPath:方法中有兩個獲得重用cell的方法
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]

請問他們有什麼區別?
當我用 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: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'

------解決方案--------------------------------------------------------
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier;
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
NS_AVAILABLE_IOS(6_0); // newer


區別在這兒

------解決方案--------------------------------------------------------
1 這個方法在SDK5.0是運行不起來的。
2 如果需要使用這個方法,你必須使用配套的方法來一起用,下面兩個配套方法:
// 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 比如你已經用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";
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      //設置你的cell

而只需要


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];


這樣就夠了,這下你明白了嗎?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章