一个UIView子类,两个不同的.xib文件

时间:2015-03-31 00:12:20

标签: ios uitableview ipad uiview xib

如果我有以下文件:

MyTableViewCell.h
MyTableViewCell.m
MyTableViewCell.xib
MyTableViewCell~ipad.xib

在IB中,如果我将一个单元指定为类类型“MyTableViewCell”,那么在iPad设备上如何从MyTableView~ipad.xib加载它?我试过这个:

@implementation MyTableViewCell

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        if (IPAD) {
            self = [UIView viewWithNib:@"MyTableViewCell~ipad"];
        }
        else {
            //iphone
        }
    }
    return self;
}

这显然是错误的并且会导致无限循环,但会让我知道我正在尝试做什么。如果我在iPad上,我希望为我指定为MyTableViewCell的任何单元格加载MyTableViewCell~ipo.xib。我想如果我把它命名为~ipad它应该自动工作,但这似乎只适用于视图控制器。

1 个答案:

答案 0 :(得分:0)

您必须在TableView数据源函数中进行单元格加载。你可以这样做:

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"MyTableViewCell";
    MyTableViewCell* cell = (MyTableViewCell*) ([tableView dequeueReusableCellWithIdentifier:cellIdentifier]);
    if(!cell){
        if(UI_USER_INTERFACE_IDIOM == UIUserInterfaceIdiomPhone){
            //iPhone
            [[NSBundle mainBundle] loadNibNamed:@"MyTableViewCell" owner:self options:nil]; 
        }
        else{
            //iPad
            [[NSBundle mainBundle] loadNibNamed:@"MyTableViewCell~ipad" owner:self options:nil]; 
        }
    cell = _aCell;
    _aCell = nil;
    }
    //Continue with initialization of your UI elements
}

这样,单元格的特定初始化由单元格的所有者类处理 - 通常是tableViewController。它还可以防止像你发布的那样无限循环的情况。

要使其正常工作,您必须将其添加到MyTableViewController.h

@property (retain, nonatomic) IBOutlet MyTableViewCell* aCell;

此外,您必须将MyTableViewCell XIB中的“File's Owner”类设置为tableViewController类(例如MyTableViewController)。然后将MyTableViewCell XIB中的UITableViewCell元素链接到文件所有者中的aCell属性。

请记住让TableViewController响应UITableViewDelegate和UITableViewDatasource。此外,您还必须为tableViewDelegate / Datasource实现以下函数:

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

希望这有帮助。

相关问题