簡體   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