Xamarin自定义UITableViewCell抛出System NullReferenceException

时间:2015-04-03 10:58:17

标签: c# uitableview xamarin.ios xamarin 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";

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

我在这里缺少什么?任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:6)

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

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

    return cell;
}

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

enter image description here

相关问题