Xamarin 在 iOS 中使用自定义 UITableViewCell 时抛出 NullReferenceException

Xamarin throws NullReferenceException when using custom UITableViewCell in iOS

我遇到的问题与 中讨论的问题非常相似。

然而,按照那里的答案,我的问题并没有得到解决。

我有一个习惯UITableView BoardListCell。在我的 Storyboard 中,我有一个 UITableView。它可以在我的 ViewController 中通过出口 tableView.

访问

在我的视图控制器中,我获取了数据。然后我做 tableView.Source = new BoardsTableViewSource(sourceData);

我的BoardsTableViewSource:

using System;
using System.Collections.Generic;
using Foundation;
using UIKit;

        public class BoardsTableViewSource : UITableViewSource
        {
            private List<List<Object>> data;
            Boolean normalBoards;

            public BoardsTableViewSource (List<List<Object>> data, bool normalBoards)
            {
                this.data = data;
                this.normalBoards = normalBoards;
            }

            public List<List<Object>> getData()
            {
                return data;
            }

            public override nint RowsInSection (UITableView tableview, nint section)
            {
                return data.Count;
            }

            public override string TitleForHeader (UITableView tableView, nint section)
            {
                return "Header";
            }

            public override string TitleForFooter (UITableView tableView, nint section)
            {
                return "Footer";
            }

            public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
            {
                BoardListCell cell = (BoardListCell)tableView.DequeueReusableCell("BoardTableCell");

                List<Object> cellData = data [indexPath.Row];

                cell.setData("1","!"); //I have simplified the data for this example

            }
        }
    }

调试时,我在 cell.setData() 行收到 NullReference 异常。

在 StoryBoard 中,我将 BoardListCell 的标识符设置为 BoardTableCell

BoardListCell:

public partial class BoardListCell : UITableViewCell
    {
        public static readonly UINib Nib = UINib.FromName ("BoardListCell", NSBundle.MainBundle);
        public static readonly NSString Key = new NSString ("BoardListCell");

    public BoardListCell() : base()
    {
    }

    public BoardListCell (IntPtr handle) : base (handle)
    {
    }

    public static BoardListCell Create ()
    {
        return (BoardListCell)Nib.Instantiate (null, null) [0];
    }

    public void setData(String top, String bottom)
    {
        this.exp.Text = top;
        this.playTime.Text = bottom;
    }
}

expplayTimeUILabel 的出口。我已经删除并重新添加了网点,但这并没有改变任何东西。

我不知道是什么问题。我唯一能想到的是因为我正在使用我用 StoryBoard 制作的 UITableView 并通过插座访问它。不过,我不知道是什么问题...

DequeueReusableCell 将 return 如果找不到合适的单元格进行重用,则为 null。因此,您需要在引用您的单元格之前明确检查它:

BoardListCell cell = (BoardListCell)tableView.DequeueReusableCell("BoardTableCell");

if (cell == null) {
  cell = new BoardListCell();
}