简体   繁体   中英

Outlets in Xamarin custom TableViewCell are null

I am trying to use a custom UITableViewCell. I am able to get the cell to instantiate, so that it is not null. However, all of the UILabel outlets in the cell are null. Thus, I am getting a null pointer exception.

This is similar to iOS custom TableViewCell class subviews return null and Label in custom cell is null when populating UITableViewController . Nevertheless, neither solutions have solved my problem. They suggest to make sure the identifier matches, which it does. They also tell me to register the cells for reuse, which I also do.

I have made sure that my identifier in the Xib file of the cell matches what I am using.

Xcode 中的 Table View Cell 显示标识符

In my Source class:

public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
    tableView.RegisterClassForCellReuse(typeof(BoardListCell), new NSString(BoardListCell.Key));
    var cell = (BoardListCell) tableView.DequeueReusableCell(BoardListCell.Key);
    if (cell == null) 
    {
        var nib = UINib.FromName(BoardListCell.Key, NSBundle.MainBundle);
        cell = (BoardListCell)nib.Instantiate (null, null) [0];
    }

    cell.setData("top", "not top"); //Sample data
    return cell;
}

In my BoardListCell class:

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 void setData(String top, String bottom)
    {
        exp.Text = top;
        playTime.Text = bottom;
    }
}

When I debug, the cell is being created. However, its outlets are null. If I instantiate them in the constructor, I don't get the error, but this obviously defeats the purpose of making prototypes in xcode as it wipes out the layout, etc.

I was having the same issue described above. The solution for me was to remove the call to TableView.RegisterClassForCellReuse(typeof(YourCustomeTableCell), "YourTableCellName");

If you created the Cell in the Xcode designer, there is no need to register the Cell.

Hope this helps anyone still having this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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