The first is the initWithCoder method: Because developers use AutoLayout in storyboard, and view initialization in storyboard does not use a common initWithFrame method, it uses initWithCoder methods to initialize the view. So the custom control has initialization logic (such as setting the default value of the variable), and be careful not to write it only in the initWithFrame method.
The second is UIView the translatesAutoresizingMaskIntoConstraints attribute, and if you use AutoLayout, you do not need to convert the old autoresizingmask to AutoLayout constraint. This property is by default YES , but it seems that initWithCoder the control translatesAutoresizingMaskIntoConstraints is no longer storyboard when it is called when the method is created.
The third is UIView the contentMode property, if you need to refresh after AutoLayout changes the size of the control drawRect , you need to set the contentMode property to UIViewContentModeRedraw . Another common custom control relies on methods that are layoutSubviews automatically called, and there's no need to worry.
Then, the initialization of the custom control can be written like this:
//UIView Construction Method- (ID) initWithFrame: (cgrect) arect{if(self =[Super Initwithframe:arect])) {[Self commoninit]; } returnSelf ;}//for Storyboard- (ID) Initwithcoder: (nscoder*) coder{if(self =[Super Initwithcoder:coder])) {[Self commoninit]; } returnSelf ;}- (void) commoninit{/*here to start initializing*/ //If you need to call DrawRect again, set Contentmode to UiviewcontentmoderedrawSelf.contentmode =Uiviewcontentmoderedraw; //conversion of AutoLayout from autoresizing is not allowed constraints//looks like storyboard when you call the Initwithcoder method when you create it, Translatesautoresizingmaskintoconstraints is no.Self.translatesautoresizingmaskintoconstraints =NO;}
IOS: Getting custom controls to fit AutoLayout attention issues