Henson Fang
Henson Fang

Reputation: 1207

How to add different constraints depend on iPhone screen size?

This is my xib file viewed as iPhone6/iPhone7,it looks good.

enter image description here

but if i turn it into iPhoneSE,it becomes abnormal.

enter image description here

Becasue the space blank doesn't change when the device changes,and i can not change the space constraint adapting to device without code.

Upvotes: 2

Views: 1721

Answers (3)

Yahya Alshaar
Yahya Alshaar

Reputation: 163

you shouldn't have to add different constraints depend on iPhone screen size! since constraints works perfectly with any screen size

just make a simple fix in layout constraints:

The problem: So what I am see that you have a problem with UIScrollView height it seems you set a fixed height constraint for UIScrollView

The Solution: first you need to remove the height constraint for UIScrollView second just add a height constraint to UISCrollView equal to parent screen height and give it a percentage

Note: how to put percentage in constraint -> highlight the constraint and then from attributes inspector there is an attribute named Multiplier it takes value form 0.0 to 1

Upvotes: 1

PGDev
PGDev

Reputation: 24341

Try following constraints:

enter image description here

Output: iPhone 6/7

enter image description here

Output: iPhone SE

enter image description here

Specify your requirements more clearly, so that I can help you more.

Upvotes: 1

elk_cloner
elk_cloner

Reputation: 2149

You need to make constants for supporting all devices like this.

var SCREEN_WIDTH = UIScreen.main.bounds.size.width
var SCREEN_HEIGHT = UIScreen.main.bounds.size.height
var BASE_SCREEN_HEIGHT:CGFloat = 667.0
var SCREEN_MAX_LENGTH = max(SCREEN_WIDTH, SCREEN_HEIGHT)
var ASPECT_RATIO_RESPECT_OF_7 = SCREEN_MAX_LENGTH / BASE_SCREEN_HEIGHT

I suppose your base layout is iPhone 7 that is your design resides in iPhone 7 layout.

Now create a function which will help to update your constraint according to device. like this.

func updateConstraint() {
    topConstantOfYourLabel.constant = 10*ASPECT_RATIO_RESPECT_OF_7
}

Call this method in viewDidLoad and your layout is just fine.

Note: For landscape mode you need to make some changes depending on your needs.I assume that you are supporting only portrait mode.

Upvotes: 0

Related Questions