Correct way to load a Nib for a UIView subclass

前端 未结 6 1943
挽巷
挽巷 2020-11-29 18:36

I am aware this question has been asked before but the answers are contradicting and I am confused, so please don\'t flame me.

I want to have a reusable UIView

6条回答
  •  囚心锁ツ
    2020-11-29 19:07

    MyViewClass *myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0]
    

    I'm using this to initialise the reusable custom views I have.


    Note that you can use "firstObject" at the end there, it's a little cleaner. "firstObject" is a handy method for NSArray and NSMutableArray.

    Here's a typical example, of loading a xib to use as a table header. In your file YourClass.m

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        return [[NSBundle mainBundle] loadNibNamed:@"TopArea" owner:self options:nil].firstObject;
    }
    

    Normally, in the TopArea.xib, you would click on File Owner and set the file owner to YourClass. Then actually in YourClass.h you would have IBOutlet properties. In TopArea.xib, you can drag controls to those outlets.

    Don't forget that in TopArea.xib, you may have to click on the View itself and drag that to some outlet, so you have control of it, if necessary. (A very worthwhile tip is that when you are doing this for table cell rows, you absolutely have to do that - you have to connect the view itself to the relevant property in your code.)

提交回复
热议问题