Xamarin自定义UITableViewCell引发System NullReferenceException异常

4
我正在为iOS创建一个Xamarin应用程序,并在storyboard中添加了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";

它说:“对象引用未设置为对象的实例。”
我在这里缺少什么?任何帮助都将不胜感激。
1个回答

6

你已经接近成功了 - 不要自己创建新的单元格,让iOS去完成它并出列结果。

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

    return cell;
}

请注意,“MainMenuCell”是来自故事板的动态原型单元格的标识符,您可以随意命名它,但它必须在故事板和您的数据源中保持一致。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接