UITableView 自定义单元格 IBOutlets 为零

UITableView custom cell IBOutlets are nil

我创建了一个 class,它是 UITableViewCell 的子class,我还为它创建了一个 xib 文件。

xib 文件中,我添加了一个 UITableViewCell,然后给它一个标识符 "ChatCell",然后在我的 class 中,我尝试使用这个自定义单元格像这样:

static NSString *CellIdentifier =  @"ChatCell";
ChatCustomCell *cell = (ChatCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

在 class 中,我提供了 UIlabelIBOutlet 并将其连接到我在 xib 中创建的 UILabel 之一,但是每当创建单元格时,UILabel 都会保持 nil.

为什么会这样?

您需要先在 ViewController 中注册您的自定义 Xib 文件。

来自Apple Docs on registerClass:forCellReuseIdentifier:

call this method or the registerClass:forCellReuseIdentifier: method to tell the table view how to create new cells. If a cell of the specified type is not currently in a reuse queue, the table view uses the provided information to create a new cell object automatically.

例如在设置 tableView delegate 和 dataSource 之后,在你的 viewDidLoad 中写下这一行:

[yourTableView registerNib:[UINib nibWithNibName:@"ChatCustomCell" bundle:nil] forCellReuseIdentifier:@"ChatCell"];

如果不这样做,您的 TableView 将无法加载 Cell Nib 文件,这将导致 Cell 的 IBOutlets 为零。

对于你的xib cell可能是returns nil对于你的cell,写这段代码可能对你有帮助。

ChatCustomCell *cell = (ChatCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]

if (cell == nil)
{
    NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"nibName" owner:self options:nil];
    cell = [nibArray objectAtIndex:0];
}