How to use custom UITableViewCell from Interface Builder?

后端 未结 3 1815
耶瑟儿~
耶瑟儿~ 2021-01-13 06:11

I want to be able to design my own UITableViewCell in IB. But I keep getting a null ref exception when trying to access the label I defined in IB.

Here\'s what I\'m

相关标签:
3条回答
  • 2021-01-13 06:39

    First of all, it is a matter of design. If your table view always loads a specific number of cells with static content, like in a "Settings" view, create a custom cell for every row you want and connect each one with an outlet.

    If this is not the case, then you have two options:

    1. Create a class that inherits the UITableViewCell and every view you want in it programmatically, forgetting Interface Builder.
    2. Add a new iPhone View with Controller, replace the view in there and treat it like you did. Except for the fact that you will have to connect your cell with an outlet in the File's Owner. So when you instantiate that controller, all your cell's subviews will be ok.

    It is not an overkill, or at least, Apple recommends it: click and go to the "Loading Custom Table-View Cells From Nib Files" paragraph

    PS: Just had a similar situation and this is the way I've done it. In MonoTouch, for this example, you do not have to LoadNib anything. Just do this inside the GetCell override in your table's source:

    using (CellController controller = new CellController())
    {
    
         cell = (CustomCell)controller.View;
    
    }
    

    Maybe even declare an extra outlet inside the CellController object to avoid casting from UIView.

    0 讨论(0)
  • 2021-01-13 06:39

    Check this link. This is a very interesting article for creating a custom TableViewCell. I think the error is due to the asynchronous loading of the xib provided by Monotouch.

    You have to provide your own costructor like this:

    public TestCellView(string sKey) //: base(UITableViewCellStyle.Default, sKey)
    {
        MonoTouch.Foundation.NSBundle.MainBundle.LoadNib ("YOUR NIBNAME", this, null);
    }
    

    Hope this helps!

    0 讨论(0)
  • 2021-01-13 06:44

    You can not reference any outlets until the Nib is loaded. There is a method that you can override that will tell you "Your NIB is loaded, you can now access the fields". Until that point, referencing those objects will always return null.

    0 讨论(0)
提交回复
热议问题