如何正确加载iOS中的nib的子视图?

时间:2014-09-02 09:54:32

标签: ios objective-c iphone uitableview uiview

我在UIView内有一个UITableViewCell(假设是一个容器)。我想将另一个UIView作为子视图添加到此容器中。但是我能够加载subView但它没有显示在每个单元格。我这样做的原因是因为我想从nib文件加载两个不同的UIViews到容器上,这取决于段控制点击。所以这就是我的意思做。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *cellIdentifier = @"Cell";
static NSString *expandedCellIdentifier = @"ExpandedCell";
if (!isExpanded) {

    ListCell *cell =(ListCell*) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell==nil) {
        NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"ListCell" owner:self options:nil];
        cell = nibs[0];
    }

    cell.Name.text = [[bArray objectAtIndex:indexPath.row]valueForKey:@"Name"];
   return cell;

}

else{


   expCell =(ExpandedCell*) [tableView dequeueReusableCellWithIdentifier:expandedCellIdentifier]; //Made this global iVar to refrence it from other methods. 
   if (expCell==nil) {
        NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"ExpandedCell" owner:self options:nil];
        expCell = nibs[0]; 
   lDView = [[[NSBundle mainBundle]loadNibNamed:@"lDView" owner:self options:nil]firstObject]; //lDView is a UIView subclass.
   [lDView setFrame:CGRectMake(0, 0, 225, 90)];
   [lDView setBackgroundColor:[UIColor grayColor]];
    //more code.
  }

     return expCell;
    }

    return nil;

   }

现在我将这个' lDView '添加到subView后用这样的按钮填充它。

  -(void)addButtons{
    //Add buttons here
    [lDView.containerScrollView addSubview:btn]; 
   [expandedCell.containerView addSubview:lDView]; //Doesn't add it to each and every table View cell.Its loading sometimes and sometimes doesn't show up. 

1 个答案:

答案 0 :(得分:0)

你在这里犯了很多错误。首先不要运行此代码:

lDView = [[[NSBundle mainBundle]loadNibNamed:@"lDView" owner:self options:nil]firstObject];
[lDView setFrame:CGRectMake(0, 0, 225, 90)];

cellForRowAtIndexPath方法内。每次显示一个单元格时(甚至向上/向下滚动)都会调用此方法。应该加载一次nib并复制/修改视图。

你要做的第二个听起来非常像原型细胞的原因。为什么不为每种情况构建一个单元格并根据使用情况加载正确的单元格,而不是每次加载一个单元格并添加它。这是更好的封装,更容易维护代码,因为在viewController中没有任何修改。

另外,如果您不熟悉objective-c,我会考虑学习Storyboards + autoLayout。 AutoLayout有点难以学习,因为它与标准编码完全不同,它相当于响应式网页设计。我个人认为在界面构建器中处理UITableView和UITableViewCells的次数要容易一些,因为你可以快速启动原型单元并调用正确的单元格。