首页 > 解决方案 > UINib 的 Xamarin DequeueReusableCell 始终产生 null

问题描述

我创建了一个简单的视图控制器,上面有一个表格视图。然后,我创建了一个 .xib 文件来设计将进入表格的 UITableViewCells。

无论我尝试什么GetCell都找不到 UITableViewCell 笔尖。我经历了名称/身份和演员表的所有变体。我对 Xamarin 和 c# 很陌生,所以我可能缺少一些简单的东西。

视图控制器:

public partial class ScheduleViewController : BaseViewController<ScheduleViewModel>
{
    [Export("initWithBundle:owner:extras:")]
    public ScheduleViewController(NSBundle bundle, UIViewController owner, string extras) : base("ScheduleViewController", bundle, owner, extras)
    {
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        Dictionary<string, List<string>> itemData = new Dictionary<string, List<string>>()
        {
            {"phones", new List<string>() {
                "Android",
                "iOS",
                "Windows Phone",
                "Other",
                "The Thing"
            }},
            {"computers", new List<string>() {
                "osx",
                "windows",
                "linux"
            }}
        };

        UITableView table = new UITableView(View.Bounds);
        table.Source = new ScheduleTableViewSource(itemData);
        table.SeparatorStyle = UITableViewCellSeparatorStyle.None;
        Add(table);
    }

UITableVIewCell 类:

public partial class WorkCell : UITableViewCell
{
    public static readonly NSString Key = new NSString("WorkCell");
    public static readonly UINib Nib;

    static WorkCell()
    {
        Nib = UINib.FromName("WorkCell", NSBundle.MainBundle);
    }

    protected WorkCell(IntPtr handle) : base(handle)
    {
        // Note: this .ctor should not contain any initialization logic.
    }
}

工作单元 .xib 文件

在此处输入图像描述

在此处输入图像描述

表视图数据源:

    public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
    {
        // always null
        UINib nib = UINib.FromName("WorkCellContainer", NSBundle.MainBundle);
tableView.RegisterNibForCellReuse(nib, "workItemCell");
        var cell = (WorkCell)tableView.DequeueReusableCell ("workItemCell");

        return cell;
}

标签: c#iosxamarin

解决方案


不需要在 GetCell 方法中加载 nib。要使用 xib 中的自定义单元格,您只需执行以下操作:

  • 使用上下文菜单创建 xib(<Add/New File> 选择iOS,选择Table View Cell

  • 在 ViewController 子类中注册 nib 以供单元重用

  • 设置重用标识符(为简单起见,只需使用与单元名称相同的名称)

  • 当使单元出队时,使用重用标识符

注册笔芯

在您的 UITableViewController 子类中ViewDidLoad(例如,在设置 DataSource 之前)添加以下内容:

table.RegisterNibForCellReuse(WorkCell.Nib, WorkCell.Key);

为单元设置重用标识符

重用标识符

出列单元格

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
    var cell = tableView.DequeueReusableCell(WorkCell.Key, indexPath) as WorkCell;

    //set the data in work cell here


    return cell;
}

在模拟器中测试

在模拟器中测试


推荐阅读