繁体   English   中英

iOS自定义TableViewCell类子视图返回null

[英]iOS custom TableViewCell class subviews return null

我使用Xamarin iOS设计器为我的TableView设计自定义TableViewCell类。 但是除了单元本身之外,所有单元子视图属性(出口)都返回null。

我的自定义单元类:

partial class VehiclesTableCell : UITableViewCell
{
    public VehiclesTableCell(IntPtr handle) : base(handle) { }

    public void UpdateCell(string licensePlate) {
        licensePlateLabel.Text = licensePlate; //hit the null reference exception for licensePlateLabel 
    }
}

生成的部分类:

[Register ("VehiclesTableCell")]
partial class VehiclesTableCell
{
    [Outlet]
    [GeneratedCode ("iOS Designer", "1.0")]
    UILabel licensePlateLabel { get; set; }

    void ReleaseDesignerOutlets ()
    {
        if (licensePlateLabel != null) {
            licensePlateLabel.Dispose ();
            licensePlateLabel = null;
        }
    }
}

和我的Table Source类的GetCell:

public class VehiclesTableSource : UITableViewSource
{
    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) {

        // Dequeueing the reuse cell
        var cell = (VehiclesTableCell)tableView.DequeueReusableCell(new NSString(typeof(VehiclesTableCell).Name));

        // Set cell properties
        cell.UpdateCell(LicensePlate);

        // Return the cell with populated data
        return cell;
    }
}

我们看到genereted代码有licensePlate的出口,那么为什么它的属性为null? 故事板是不是应该自动实例化其所有子视图? 至少它发生在所有其他情况。

在此输入图像描述

我的自定义TableViewCell遇到了同样的问题。 我发现问题出在TableView.RegisterClassForCellReuse (typeof(MyCell), MyCellId) 我不得不将其更改为TableView.RegisterNibForCellReuse(UINib.FromName("MyCell", NSBundle.MainBundle), MyCellId)以便加载我的.xib。

我自己遇到过这个问题。 这就是我解决它的方法:

  1. 在自定义单元格的构造函数中实例化子视图的组件。 在你的情况下,像:

    public VehiclesTableCell(IntPtr handle) : base(handle) { licensePlateLabel = new UILabel(); }

  2. 覆盖方法LayoutSubviews:

    public override void LayoutSubviews () { base.LayoutSubviews (); licensePlateLabel.Frame = new RectangleF(63, 5, 33, 33); // Your layout here }

本指南中的信息让我走得很远,但理想情况下,如果没有在IOS设计器中定义子视图组件的情况下手动实例化和布局子组件,则可以实现此目的。 希望有人可以用更好的方式来实现这个目标......

编辑:我遇到了这个答案 ,解释了为什么我无法绑定我在设计器中创建的自定义表格单元格。 TLDR:确保Identity -> ClassTable View Cell -> Identifier都设置为检查器窗口中的自定义表视图单元类名称。

我有同样的问题,据我所知,如果你使用的是故事板,你可以在iOS设计器的表格单元属性中输入你的自定义类名,它应该可以工作。 调用RegisterClassForCellReuse()是导致null子视图问题的原因。 一旦我删除了该方法调用它似乎工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM