Xamarin 自定义 UITableViewCell 抛出系统 NullReferenceException

2023-12-31

我正在为 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 和数据源相同。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Xamarin 自定义 UITableViewCell 抛出系统 NullReferenceException 的相关文章

随机推荐