Reference of prototype cells from IB

2019-09-05 09:41发布

I am doing iOS project with storyboards in MonoTouch.

I have the custom class of UITableView (myCustomTableFoo) and specified the prototype cells of this class in IB. Then I want to instance this class programmatically. The bad thing it's lacking the prototype cells, and I don't know how to insert that prototype cells to my programmatically created table object.

I have a storyboard and I want to use my prototype cells from IB in all my inherited table classes. I think MonoTouch could be pretty similar to Objective-c in this case.

1条回答
Summer. ? 凉城
2楼-- · 2019-09-05 10:06

You could use

this._tableView.RegisterClassForCellReuse(typeof(MyCell), new NSString("MyReuseIdentifier"));

then you can dequeue your cell using

this._tableView.DequeueReusableCell("MyReuseIdentifier");

the cell would be automatically instantiated. You do need to register your class using [Register("MyCell") and it should have a constructor like

public MyCell(IntPtr handle) : base(handle) {

}

One thing though, I don't think you can reuse the cell you defined in your storyboard. If you want to reuse the same cells in different TableView instance, you can create a unique Nib for your cell and then something like that would do the trick:

public partial class MyCell : UITableViewCell {

    private MySuperCellView _mySuperNibView;

    public MyCell (IntPtr handle) : base (handle) {

    }

    private void checkState() {
        // Check if this is the first time the cell is instantiated
        if (this._mySuperNibView == null) {
            // It is, so create its view
            NSArray array = NSBundle.MainBundle.LoadNib("NibFileName", this, null);
            this._mySuperNibView = (MySuperCellView)Runtime.GetNSObject(array.ValueAt(0));
            this._mySuperNibView.Frame = this.Bounds;
            this._mySuperNibView.LayoutSubviews();

            this.AddSubview(this._mySuperNibView);
        }
    }

    public object cellData {
        get { return this._mySuperNibView.cellData; }
        set {
            this.checkState();
            this._mySuperNibView.cellData = value;
        }
    }
}

Here I'm using a generic view defined on an external Nib. I manually instantiate it when feeding the data into the Cell if it doesn't has been yet instantiated. It happens typically at the first time the Cell was instantiated.

查看更多
登录 后发表回答