Xamarin 自定义 UITableViewCell 抛出系统 NullReferenceException

Xamarin custom UITableViewCell throws System NullReferenceException

我正在为 iOS 创建一个 Xamarin 应用程序,我已经将 UITableViewCell 添加到情节提要中以赋予它我自己的风格。我确实在这个自定义的 UITableViewCell 中添加了一个 class,即 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 行中向我抛出 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 和数据源相同。