【问题标题】:One UIView subclass, two different .xib files一个 UIView 子类,两个不同的 .xib 文件
【发布时间】:2015-06-04 04:37:05
【问题描述】:

如果我有以下文件:

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~ipad.xib。我想如果我将它命名为 ~ipad,它应该可以自动工作,但这似乎只适用于视图控制器。

【问题讨论】:

    标签: ios uitableview ipad uiview xib


    【解决方案1】:

    您必须在 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 中的“文件所有者”类设置为 tableViewController 类(例如 MyTableViewController)。然后将 MyTableViewCell XIB 中的 UITableViewCell 元素链接到 File's Owner 中的 aCell 属性。

    记得让你的 TableViewController 响应 UITableViewDelegate 和 UITableViewDatasource。此外,您必须为 tableViewDelegate/Datasource 实现以下功能:

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

    希望这会有所帮助。

    【讨论】:

    • 感谢您的建议。如果我在表格视图中使用静态单元格怎么办?
    • 我仍然确定您的 MyTableViewCell 类中有一些需要设置的 IBOutlet 属性(这就是为什么您有一个 MyTableViewCell 开头的原因)。如果没有,这应该仍然有效。所有这些代码都告诉 iPad - 对于我需要在表格中创建的每个单元格,对 iPhone 使用“MyTableViewCell”,对 iPad 使用“MyTableViewCell~iPad”。
    猜你喜欢
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    相关资源
    最近更新 更多