无法将参数传递给UITableViewCell

Soh*_*ard 0 objective-c uitableview ios

我有一些不同的单元格,为此我需要将参数从我的UIViewController传递到我的UITableViewCell的子类.但它不起作用.场景如下:

MessagesViewController.m:

#import "MessagesViewController.h"
#import "MessageTableViewCell.h"

- (void)viewDidLoad
{    
    [super viewDidLoad];

    [self.tableView registerClass:[MessageTableViewCell class] forCellReuseIdentifier:MessengerCellIdentifier];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageTableViewCell *cell = (MessageTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:MessengerCellIdentifier];

    if (cell == nil) {
        cell = [[MessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MessengerCellIdentifier customParam:YES];
    }
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

MessageTableViewCell.m:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier customParam:(BOOL)customParam
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
       // **** GET Custom Parameter (customParam) HERE ??? ****/
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,customParam是我的参数.一切似乎都没问题,但是单元格不是零,所以程序失败了.

Put*_*103 5

选项1:删除该dequeueReusableCellWithIdentifier行,以便每次都创建一个新的自定义单元格.否则,您正在使用已经存在前一个customParameter设置的预先存在的单元格,无论显示的最后一个单元格设置为什么.

- 注意选项1(添加为解释为什么它是一个非常非常糟糕的想法(@Duncan C).由于你在设置你的单元格ReuseIdentifier中创建你的单元格iOS一旦它们将为你保留它们滚动屏幕以便您可以在代码要求时重复使用它们.但是您的代码永远不会要求可重复使用的单元格,因为每次表格要求下一个单元格时它会生成一个全新的单元格.这会导致高加载时间(创建一个每次使用新单元)和高内存使用(因为操作系统正在保存单元供您以后使用,而不是立即解除分配).可重用性是出于某种原因而构建的,所以除非您有特殊需要,否则不要使用选项1这样做(即便如此,你可能错了,不要这样做).

选项2:将自定义参数更改为单独的方法调用.而不是在初始化程序中创建一个新方法,清除单元格并按照新自定义参数的方式重建它.然后,您可以使用新setCustomParameter:方法重新使用单元格并修改其外观.

编辑:选项2的代码示例,尽可能简单:

在表控制器中

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageTableViewCell *cell = (MessageTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:MessengerCellIdentifier];

    if (cell == nil) {
        cell = [[MessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MessengerCellIdentifier];
    }
    [cell setCustomParam:customParam];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

在你的手机里.m

-(void)setCustomParam:(ParamType)type
{
    //Do whatever you would like right here to clear the previous
    //cell's custom information and add the new custom information
    //to this new cell.
}
Run Code Online (Sandbox Code Playgroud)