經過xib加載UITableViewCell的新方式

咱們之前一般會這樣作

- (UITableViewCell  *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
     static  NSString  *CellIdentiferId = @"MomentsViewControllerCellID";
     MomentsCell  *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentiferId];
     if (cell == nil) {
        NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"MomentsCell" owner:nil options:nil];
        cell = [nibs lastObject];
        cell.backgroundColor = [UIColor clearColor];
        

      };
        
     }
     return cell;ios

}
嚴重注意:咱們以前這麼用都沒注意太重用的問題,這樣寫,若是在xib頁面沒有設置 重用字符串的話,是不可以被重用的,也就是每次都會從新建立,這是嚴重浪費內存的,因此,須要修改啊,一種修改方式是使用以下ios5提供的新方式:
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier
還有就是在xib頁面設置好(ios5以前也能夠用的)


NSArray * nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:nil options:nil];

for (id obj in nibObjects)
{
    if ([obj isKindOfClass:[CustomTableCell class]])
    {
        cell = obj;
        [cell setValue:cellId forKey:@"reuseIdentifier"];
        break;
    } 
}
還有更經常使用的
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return[self.items count];
}
 
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"myCell"];
if(!cell)
{
cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
}
 
cell.textLabel.text =[self.items objectAtIndex:indexPath.row];
 
return cell;
}
 
可是如今有一種新的方式了,能夠採用以下的方式
採用registerNib的方式,而且把設置都放在了willDisplayCell方法中了,而不是之前咱們常常用的cellForRowAtIndexPath
這個方法我試了下,若是咱們在xib中設置了 Identifier,那麼此處的必須一致,不然會crash的
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    MyCustomCell * cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
    if (!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:@"MyCustomCell" bundle:nil] forCellReuseIdentifier:@"myCell"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(MyCustomCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.leftLabel.text = [self.items objectAtIndex:indexPath.row];
    cell.rightLabel.text = [self.items objectAtIndex:indexPath.row];
    cell.middleLabel.text = [self.items objectAtIndex:indexPath.row];
}ide

相關文章
相關標籤/搜索