Xamarin自定义UITableViewCell抛出System NullReferenceException

我正在为iOS创建一个Xamarin应用程序,我已经在故事板中添加了一个UITableViewCell,以赋予它自己的风格。 我确实为这个自定义UITableViewCell添加了一个类,即MainMenuCell。 我在单元格中添加了两个标签,并将它们与MainMenuCell.h文件连接起来,产生以下代码:

MainMenuCell.cs

using System; using Foundation; using UIKit; namespace MyProjectNamespace { public partial class MainMenuCell : UITableViewCell { public MainMenuCell (IntPtr handle) : base (handle) { } public MainMenuCell () : base () { } public void SetCellData() { projectNameLabel.Text = "Project name"; projectDateLabel.Text = "Project date"; } } } 

MainMenuCell.h(自动生成):

 using Foundation; using System.CodeDom.Compiler; namespace MyProjectNamespace { [Register ("MainMenuCell")] partial class MainMenuCell { [Outlet] UIKit.UILabel projectDateLabel { get; set; } [Outlet] UIKit.UILabel projectNameLabel { get; set; } void ReleaseDesignerOutlets () { if (projectNameLabel != null) { projectNameLabel.Dispose (); projectNameLabel = null; } if (projectDateLabel != null) { projectDateLabel.Dispose (); projectDateLabel = null; } } } } 

现在我在这里有我的UITableViewSource,我正在尝试从GetCell方法初始化MainMenuCell:

 using System; using UIKit; using Foundation; namespace MyProjectNamespace { public class MainMenuSource : UITableViewSource { public MainMenuSource () { } public override nint NumberOfSections (UITableView tableView) { return 1; } public override string TitleForHeader (UITableView tableView, nint section) { return "Projects"; } public override nint RowsInSection (UITableView tableview, nint section) { return 1; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { MainMenuCell cell = new MainMenuCell(); cell.SetCellData (); return cell; } } } 

但是,它一直在行中抛出一个System.NullReferenceException:

 projectNameLabel.Text = "Project name"; 

它说:对象引用未设置为对象的实例。

我在这里想念的是什么? 任何帮助将受到高度赞赏。

你几乎就在那里 – 不要自己创建一个新单元,让iOS完成工作并将结果出列。

 public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = (MainMenuCell)tableView.DequeueReusableCell("MainMenuCell"); cell.SetCellData(); return cell; } 

请注意,“MainMenuCell”是Storyboard中动态原型单元的标识符,您可以根据需要为其命名,但它必须与Storyboard和Datasource相同。

在此处输入图像描述