Custom controls with XIB (inherited in XIB)

  • Preface,
    development has quite a long time, remember when the line, no matter what is written pure code, never use Xib to drag a control, not to mention what storyboard. Later found that colleagues around me are using XIB to write the interface, every time I spent half a day to write the interface, he finished two hours, and the adaptation is also perfect. Slowly start trying to use XIB and storyboard.
    used XIB and storyboard for a period of time, and found that people are getting lazier and lazier, even if a very simple interface control, what is not willing to write more code, direct XIB. But one of the awkward questions is that when you use XIB to customize a view, when you’re using it on another XIB, it’s useless to just inherit, and you have to code to create it. For this, very distressed.
    got a lot of references online and got it. In order to save time for later scholars, this article is specially written.

Demo address

  • The detailed steps are as follows:
    1. creates a class that is UIView
Custom controls with XIB (inherited in XIB)
Paste_Image.png

2. creates a XIB file with the same name

Custom controls with XIB (inherited in XIB)
Paste_Image.png

3. customize your views and controls in XIB and customize the controls to the way you want them to be

Custom controls with XIB (inherited in XIB)
Paste_Image.png

4. set the File’s Owner XIB of Class for the class you created

Custom controls with XIB (inherited in XIB)
Paste_Image.png

5. links the View drag in Xib to the member variable you created, named view

Custom controls with XIB (inherited in XIB)
Paste_Image.png

6. overrides the following method in creating a class.M file

Custom controls with XIB (inherited in XIB)
Paste_Image.png
XIB will fall by creating / * * * / - (instancetype) initWithCoder: (NSCoder *) coder{self = [super initWithCoder:coder]; if (self) {[self setUI]}; return self;} / * * * / - code to create drop (instancetype) initWithFrame: (CGRect) frame{self = [super initWithFrame:frame]; if (self) {[self setUI]; return self};} / * * * / - initialization (void) ([self class]) setUI{[[NSBundle mainBundle]loadNibNamed:NSStringFromClass owner:self options:nil]; [self addSubview:self.view];} / * * * / - size self adaptation (void) drawRect: (CGRect) rect{self.view.frame = self.bounds;}

7. use
XIB to drag and drop a View directly, and then become your custom class

Custom controls with XIB (inherited in XIB)
Paste_Image.png

Code creation

CustomXibView, *view = [[CustomXibView, alloc], initWithFrame:CGRectMake (0, 0, 300, 100)];