3

我对 UITableViewCell 进行了子类化以对其进行自定义,但我认为我遗漏了一些东西,因为:1)它不起作用,2)我对一些事情感到困惑。除了自定义 .xib 文件的外观外,我还更改了 backgroundView,这部分工作正常。我最不了解/最困惑的部分是 init 方法,所以我把它贴在这里。如果事实证明这是正确的,请告诉我,以便我可以发布更多可能是原因的代码。

这是我自定义的init方法。我对“风格”的想法有点困惑,我想我只是返回一个具有不同背景视图的普通 UITableViewCell。我的意思是,那里没有任何东西是指 .xib 或做任何事情,只是从自我改变 .backgroundView :

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier wait: (float) wait fadeOut: (float) fadeOut fadeIn: (float) fadeIn playFor: (float) playFor
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        CueLoadingView* lview = [[CueLoadingView alloc] initWithFrame:CGRectMake(0, 0, 320, 53)];
        self.backgroundView = lview;

        [self setWait:wait]; // in turn edits the lview through the backgrounView pointer
        [self setFadeOut:fadeOut];
        [self setFadeIn:fadeIn];
        [self setPlayFor:playFor];
    }
    return self;
}

除了 .xib 和几个 setter 和 getter 之外,这是我的代码中唯一真正的部分,它与检索单元格有关。

附加信息:

1)这是我的.xib,它与班级相关联。 在此处输入图像描述

2)这是调用/创建 UITableView(委托/视图控制器)的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"CueTableCell";

    CueTableCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[CueTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier wait:5.0 fadeOut:1.0 fadeIn:1.0 playFor:10.0];
        [cell updateBarAt:15];
    }

    return cell;
}
4

3 回答 3

12

在 nib 文件中创建自定义表格视图单元格的最简单方法(自 iOS 5.0 起可用)是registerNib:forCellReuseIdentifier:在表格视图控制器中使用。最大的优点是,dequeueReusableCellWithIdentifier:如果需要,它会自动从 nib 文件中实例化一个单元格。你不再需要这个if (cell == nil) ...零件了。

viewDidLoad您添加的表视图控制器中

[self.tableView registerNib:[UINib nibWithNibName:@"CueTableCell" bundle:nil] forCellReuseIdentifier:@"CueTableCell"];

cellForRowAtIndexPath你身上

CueTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CueTableCell"];
// setup cell
return cell;

从 nib 文件加载的单元格使用 实例化initWithCoder,如有必要,您可以在子类中覆盖它。对于 UI 元素的修改,您应该重写awakeFromNib(不要忘记调用“super”)。

于 2013-03-23T20:03:28.750 回答
1

您必须改为从 .xib 加载单元格:

if ( cell == nil ) {
    cell = [[NSBundle mainBundle] loadNibNamed:@"CellXIBName" owner:nil options:nil][0];
}

// set the cell's properties
于 2013-03-23T20:00:54.283 回答
1
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"CueTableCell";

    CueTableCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CueTableCell XibName" owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        cell = [array objectAtIndex:0];
    }

    return cell;
}
于 2013-03-23T20:01:26.960 回答