iphone - 自定义 UITableViewCell 未使用 .xib(很可能是因为 init 方法中的缺陷)

标签 iphone ios objective-c xcode uitableview

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

这是我自定义的 init 方法。我对“样式”的想法有点困惑,我想我只是返回一个带有不同 backgroundView 的普通 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,链接到类。 enter image description here

2) 这是调用/创建 UITableView(委托(delegate)/ View Controller )的代码:

- (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;
}

最佳答案

在 nib 文件中创建自定义表格 View 单元格的最简单方法(自 iOS 5.0 起可用)是在表格 View Controller 中使用 registerNib:forCellReuseIdentifier:。最大的优点是 dequeueReusableCellWithIdentifier: 然后会在必要时自动从 nib 文件中实例化一个单元格。您不再需要 if (cell == nil) ... 部分。

在你添加的 TableView Controller 的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”)。

关于iphone - 自定义 UITableViewCell 未使用 .xib(很可能是因为 init 方法中的缺陷),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15591364/

相关文章:

iphone - XCode 探查器 "Leaked Blocks"表中的条目是否暗示确实存在泄漏?

ios - 使用 UISlider 更改字体大小

iOS Collection 复制在 NSArray 和 NSDictionary 中打印不同的地址

iphone - Cydia 应用程序可以使用 UIFileSharingEnabled 选项吗?

iphone - 无法弄清楚为什么我的应用程序在使用 NSKeyedArchivers/NSKeyedUnarchivers 时崩溃

ios - 在 UIViewController 中设置 RootViewController

ios - 比较两个数组和映射等于对象

c - 递增 c 指针

iphone - 连接从自定义类加载的 XIB 到 Storyboard的操作

ios - Swift - 在 CGPoint 比较颜色