将xibs中的UIViews加载到UITableView页眉,页脚和单元格中?

时间:2011-10-10 16:52:42

标签: ios uitableview interface-builder

我有一个弹出视图,我将其实现为一个完整大小的透明视图,其中包含一个较小的UITableView。我想要做的是在xibs中设计视图然后将它们加载到UITableView部分,如页眉,页脚和单元格。我希望这一切尽可能地包含在内,只使用1个视图控制器和多个xib。

我可以轻松地在一个视图控制器中执行页眉和页脚。我制作了一个标头xib,在IB中我将各种组件与我的一个视图控制器中的IBOutlets相关联。然后在视图控制器中,我实现了相应的UITableView委托,在viewForHeaderInSection中我使用以下方法加载xib:

UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];

if (section == 0)
{
    [headerView setBackgroundColor:[UIColor colorWithRed:0.000 green:0.002 blue:0.334 alpha:0.850]];

    NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"TableHeader" owner:self options:nil];
    UIView *nibView = [nibObjects objectAtIndex:0];

    headerView.autoresizesSubviews = YES;
    [headerView addSubview:nibView];

    [headerLabel1 setText:@"blah"];
    [headerLabel2 setText:@"blah"];
    [headerLabel3 setText:@"blah"];
    [headerLabel4 setText:@"blah"];
}
else 
{
    [headerView setBackgroundColor:[UIColor clearColor]];
}

return headerView;

虽然我不能为细胞工作做同样的事情。我尝试了相同的过程,从nibObjects抓取xib并将视图添加到单元格的视图中,但它不起作用。我通过为单元格创建一个带有xib的视图控制器类来实现它,然后在viewDidLoad方法中包含我的UITableView的视图控制器内部我创建了该VC的2个实例:

 cell1 = [[CellViewController alloc] initWithNibName:@"CellViewController" bundle:nil weatherData:weatherItems];

[cell1 setTitle:@"1"];

cell2 = [[CellViewController alloc] initWithNibName:@"CellViewController" bundle:nil weatherData:weatherItems];

[cell2 setTitle:@"2"];

然后在cellForRowAtIndexPath中,我将cell1和cell2视图添加到当前单元格的视图中。这是代码:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];

if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];

    if(indexPath.row == 0)
        [cell addSubview:cell1.view];
    else
        [cell addSubview:cell2.view];

    cell.userInteractionEnabled = NO;
}

return cell;

然后我使用self.title(在包含UITableView的视图控制器中设置)来处理在单元的视图控制器内设置IBOutlet组件。

这种方法有效,但我想只有1个VC类和单独的xib用于标题,页脚和1 xib可以反复使用的单元格,只需要能够以不同的方式设置单元格的组件在行上。

我想这样做,以便可以轻松地将页眉,页脚和单元格与弹出窗口整体分开。或者

另外,有没有办法在1 xib中创建多个UIViews并单独使用它们?那就是我的头部,页脚和单元格也只有一个xib而不是3个。

这是我尝试实现的功能的最佳方法吗?

唐卡!

0 个答案:

没有答案