【问题标题】:Does Custom UITableViewCell nib requires a Custom OBJ-C class as the file owner?自定义 UITableViewCell 笔尖是否需要自定义 OBJ-C 类作为文件所有者?
【发布时间】:2009-08-11 16:59:04
【问题描述】:

我正在尝试弄清楚如何将自定义 UITableViewCell 实现为笔尖...我知道 UITableView 是如何工作的,但是使用 Interface Builder NIB 实现自定义单元格会增加复杂性...但有助于灵活性...我的问题这是:

在 Interface Builder 中设计完自定义单元后,我们是否需要像在 ViewControlers 中那样创建一个 Obj-C 自定义类来指定为文件所有者?

【问题讨论】:

    标签: uitableview interface-builder


    【解决方案1】:

    您可以使用自定义类作为文件的所有者,但您不必这样做。我将向您展示两种从 NIB 加载表格单元格的技术,一种使用文件所有者,另一种不使用。

    在不使用文件所有者的情况下,这是一种从 NIB 加载表格单元格的方法:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:@"MyID"];
        if (!myCell) {
            NSBundle *bundle = [NSBundle mainBundle];
            NSArray *topLevelObjects = [bundle loadNibNamed:@"MyNib" owner:nil options:nil];
            myCell = [topLevelObjects lastObject];
        }
        /* setup my cell */
        return myCell;
    }
    

    上面的代码很脆弱,因为将来如果你修改XIB以获得更多的顶级对象,这个代码可能会因为从“[topLevelObjects lastObject]”中获取错误的对象而失败。但它在任何其他方面都不脆弱,所以这种技术很好用。

    为了更明确、更健壮,您可以使用文件的所有者和插座,而不是使用顶级对象。这是一个例子:

    @interface MyTableViewDataSource : NSObject {
        UITableViewCell *loadedCell;
    }
    @property (retain) UITableViewCell *loadedCell;
    @end
    
    @implementation MyTableViewDataSource
    
    @synthesize loadedCell;
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:@"MyID"];
        if (!myCell) {
            [[NSBundle mainBundle] loadNibNamed:@"MyNib" owner:self options:nil];
            myCell = [[[self loadedCell] retain] autorelease];
            [self setLoadedCell:nil];
        }
        /* setup my cell */
        return myCell;
    }
    @end
    

    【讨论】:

    • 我正在使用第一种方法,因为它似乎被很多开发人员使用...但是,我更喜欢第二种方法,因为它最终让我可以更好地控制我们在自定义中可以做什么类来放置更多的初始化代码......更多的面向对象......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    相关资源
    最近更新 更多