![](/img/trans.png)
[英]Custom UITableViewCell without dequeueReusableCellWithIdentifier
[英]UITableViewCell dequeueReusableCellWithIdentifier with custom initializer
我正在使用[UITableView registerClass: forReuseIdentifier:]
和[UITableView dequeueReusableCellWithIdentifier:]
来排队和出列UITableViewCells。
例如,在viewDidLoad中:
[self.storeTableView registerClass:[StoreLineGraphCell class] forCellReuseIdentifier:@"StoreLineGraphCellIdentifier"];
在cellForRowAtIndexPath中:
StoreLineGraphCell *cell = (StoreLineGraphCell*)[self.storeTableView dequeueReusableCellWithIdentifier:@"StoreLineGraphCellIdentifier"];
在这样做时,为initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
调用initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
初始值设定项。 问题是我需要使用自定义初始化程序来创建具有必要选项的单元格。 例如,能够做这样的事情:
StoreLineGraphCell *cell = [[StoreLineGraphCell alloc] initWithReuseIdentifier:@"StoreLineGraphCell" isLocked:YES isUpcoming:YES];
registerClass
和dequeue
模式似乎不可能这样。 我想把它保存在初始化程序中,因为它应该只运行一次,而不是每次单元格出列时。 有没有正确的方法来实现这一目标?
当你遵循通常的单元重用模式时(就像你使用寄存器类和出队一样),我看不到一种易于实现的方法。
如果我是你,我会创建一个额外的初始化方法(不遵循通常的obj-c init
模式)或简单地设置并在dequeueReusableCellWithIdentifier
调用之后调用它。
StoreLineGraphCell *cell = (StoreLineGraphCell*)[self.storeTableView dequeueReusableCellWithIdentifier:@"StoreLineGraphCellIdentifier"];
[cell furtherInitWithLocked:YES andUpcoming:NO]; // ... or so
您正在使用正确的registerClass和dequeue方法,但是为了调用/设置自定义属性,您应该配置创建单独的方法并调用它。
而不是这个:
StoreLineGraphCell *cell = [[StoreLineGraphCell alloc]
initWithReuseIdentifier:@"StoreLineGraphCell" isLocked:YES isUpcoming:YES];
你可以这样做:
StoreLineGraphCell *cell = // get the dequeue cell
[cell configure];
在configure方法中,您可以设置属性,如下所示:
-(void) configure
{
self.isLocked = YES;
self.isUpcoming = YES;
}
这是我今天遇到的一个常见问题。
但是,它可以像这样解决。
因为在dequeueReusableCellWithIdentifier
方法调用之前注册的单元类,在执行之后
cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]
,
单元格总是不是零并且返回
- initWithStyle:style reuseIdentifier:reuseIdentifier
。
看来您无法自定义自己的init方法。
但是,如果您之前没有注册单元类,那么如果tableview没有可重用的单元格,则dequeueReusableCellWithIdentifier
将返回nil 。
因此,我们应该检查dequeueReusableCellWithIdentifier
返回的单元格值,如果它是nil,那么我们可以使用我们的自定义方法初始化它。
cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]
if (!cell) {
cell = /* custom init method */
}
那已经完成了! 如果我们要自定义子类cell init方法,那么之前不要注册cell类 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.