Correct way to load a Nib for a UIView subclass

前端 未结 6 1934
挽巷
挽巷 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 18:51

    If you want to keep your CustomView and its xib independent of File's Owner, then follow these steps

    • Leave the File's Owner field empty.
    • Click on actual view in xib file of your CustomView and set its Custom Class as CustomView (name of your custom view class)
    • Add IBOutlet in .h file of your custom view.
    • In .xib file of your custom view, click on view and go in Connection Inspector. Here you will all your IBOutlets which you define in .h file
    • Connect them with their respective view.

    in .m file of your CustomView class, override the init method as follow

    -(CustomView *) init{
        CustomView *result = nil;
        NSArray* elements = [[NSBundle mainBundle] loadNibNamed: NSStringFromClass([self class]) owner:self options: nil];
        for (id anObject in elements)
        {
            if ([anObject isKindOfClass:[self class]])
            {
                result = anObject;
                break;
            }
        }
        return result;
    }
    

    Now when you want to load your CustomView, use the following line of code [[CustomView alloc] init];

提交回复
热议问题