Grant Fong
Grant Fong

Reputation: 311

can i specific autolayout constraints for 4.7 and 5.5

can i specific and different constraints by just using autolayout and storyboard for 4.7 (iPhone 6) and (iPhone 6 plus)

e.g i want the icon have 50pixel for 4", 60 pixel for 4.7" and 66 for 5.5" iphone .?

Upvotes: 0

Views: 246

Answers (2)

Matteo Gobbi
Matteo Gobbi

Reputation: 17707

Hi yes you have two ways:

  • Relate the width of the icon to the width of the screen. Indeed, if you want the width of the icon to be 50px when the screen is 4'' so 320px, the multiplier is 50.0/320.0 = 0.15625:

    NSLayoutConstraint *constraint = [NSLayoutConstraint  
                                        constraintWithItem:iconImageView 
                                        attribute:NSLayoutAttributeWidth 
                                        relatedBy:NSLayoutRelationEqual 
                                        toItem:self.view 
                                        attribute:attribute:NSLayoutAttributeWidth 
                                        multiplier:0.15625 
                                        constant:0]; 
    
    [self.view addConstraint:constraint];
    

    obviously set also the constraint proportional width/height on the iconImageView. By this proportion the icon width (and so height) on iPhone 6+ will result 414*0.15625 = 64.6875;

  • the second way it is just to have an IBOutlet to the fixed width constraint of the iconImageView and change it from the code checking the width of the screen:

    if ([UIScreen mainScreen].bounds.size.width == 320.0) {
        myConstraintsWidth.constant = 50.0;
    } .... and so on
    

    Also here obviously set also the constraint proportional width/height on the iconImageView.

IMO I hugely prefer the first option. It is clean and works really well.

Cheers!

Upvotes: 1

James
James

Reputation: 81

If you were asking whether it is possible to set the constraints using Storyboard only, I'm afraid the answer is negative, which means you must implement some code.

Example: Please note this is hard-coding and not elegant, just showing you the spirit

#define SCREEN_WIDTH MIN([UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height)

- (void)setImageWidthConstraint:(NSLayoutConstraint *)imageWidthConstraint {
    if (SCREEN_WIDTH == 320) { //iPhone 5s or earlier
        imageWidthConstraint.constant = 50;
    } else if (SCREEN_WIDTH == 375) { //iPhone 6
        imageWidthConstraint.constant = 60;
    } else if (SCREEN_WIDTH == 414) { //iPhone 6 Plus
        imageWidthConstraint.constant = 66;
    }
}    

Upvotes: 0

Related Questions