XIB and StoryBoard have always been a focus of iOS development layouts, and people love using them to quickly sketch out nice graphical interfaces. In our use, there is also a problem, different models of mobile phone screen width and height are different, we set a fixed value when setting constraints, so that the screen display effect is very different. In order to have a similar effect on different phone sizes. The constraint is dynamically calculated, and then the corresponding proportional size is obtained.

We added classification attributes to the NSLayoutConstraint to dynamically evaluate the results of the constraint

We define a visual property, so we need to decorate this property with IBInspectable.

@interface NSLayoutConstraint (IBAdapter)

@property (nonatomic, assign) IBInspectable BOOL adapterScreen;

@end
Copy the code

Because the attributes added by the classification require the technique of associating objects to achieve GET and set. At the same time, import runtime.h into the. M file.

Two macros are defined to calculate the constraint size after adaptation

#define BaseWidth 375

#define AdaptW [[UIScreen mainScreen] bounds].size. Width/BaseWidth * 1.00

Implementing the set method

static char *adapterKey = "adapterKey"; -(void)setAdapterScreen:(BOOL)adapterScreen{ BOOL flag = adapterScreen; objc_setAssociatedObject(self, adapterKey, @(flag), OBJC_ASSOCIATION_RETAIN_NONATOMIC); if(adapterScreen){ self.constant = AdaptW * (self.constant); }}Copy the code

Implement the GET method

-(BOOL)adapterScreen{
   BOOL flag = objc_getAssociatedObject(self, adapterKey);
    return flag;
}
Copy the code

Now that the whole coding is done, compile the project and you’ll see that you have an adapterScreen view property on top of your constraint. Select on, and we have a good fit for this property.

The overall code is shown below