我有一个UITableView,它包含一个原型单元,在storyboard中添加了组件,并在我的CustomCell.h和.m文件中引用,CustomCell.cs如下所示:
public partial class CustomCell : UITableViewCell
{
public CustomCell(IntPtr handle) : base(handle)
{
}
public UILabel Sender
{
get
{
return senderLabel;
}
set
{
senderLabel = value;
}
}
public UILabel Subject
{
get
{
return subjectLabel;
}
set
{
subjectLabel = value;
}
}
public UILabel Date
{
get
{
return timeLabel;
}
set
{
timeLabel = value;
}
}
public UILabel Preview
{
get
{
return previewLabel;
}
set
{
previewLabel = value;
}
}
public UILabel Initials
{
get
{
return initialsLabel;
}
set
{
initialsLabel = value;
}
}
}
然后,在我的表的源文件及其GetCell方法中使用此自定义单元格来尝试向表中添加数据:
CustomCell cell = tableView.DequeueReusableCell("MailCell") as CustomCell;
cell.Sender.Text = TableItems[indexPath.Row].Sender;
cell.Subject.Text = TableItems[indexPath.Row].Subject;
cell.Preview.Text = TableItems[indexPath.Row].Preview;
cell.Date.Text = TableItems[indexPath.Row].Time;
cell.Initials.Text = "";
当您运行程序并尝试将数据添加到表中时,它会使用NullReferenceException在GetCell方法的第二行中断,这意味着它们在单元格中没有标签,或者没有要编辑的单元格。我的原型的单元格有一个标识符“MailCell”,我尝试在类中创建一个完整的构造函数,但这不起作用。我以前以编程方式将组件添加到表格的单元格中,并且工作正常,因此我可以确保将数据添加到源的代码按预期工作,并不是问题。还有什么可以测试?
它因为无法在第一行找到自定义单元格的实例而中断。 DequeueReusableCell正在寻找一个实例,如果它找不到它返回null
将您的代码更改为:
CustomCell cell = tableView.DequeueReusableCell("MailCell") as CustomCell ?? new CustomCell();