iOS Autolayout - How to set two different distances between views, depends on the screen height
You can create an NSLayoutConstraint
outlet on your view controller and connect the outlet to the activity indicator's Y constraint in your xib or storyboard. Then, add an updateViewContraints
method to your view controller and update the constraint's constant according to the screen size.
Here's an example of updateViewConstraints
:
- (void)updateViewConstraints {
[super updateViewConstraints];
self.activityIndicatorYConstraint.constant =
[UIScreen mainScreen].bounds.size.height > 480.0f ? 200 : 100;
}
Of course you will want to put in your appropriate values instead of 200
and 100
. You might want to define some named constants. Also, don't forget to call [super updateViewConstraints]
.
The problem of @Rob answer's is you should do a lot of code for each constraint.
So to resolve that, just add ConstraintLayout
class to your code and modify constraint constant value for the device that you want in the IB :
//
// LayoutConstraint.swift
// MyConstraintLayout
//
// Created by Hamza Ghazouani on 19/05/2016.
// Copyright © 2016 Hamza Ghazouani. All rights reserved.
//
import UIKit
@IBDesignable
class LayoutConstraint: NSLayoutConstraint {
@IBInspectable
var 3¨5_insh: CGFloat = 0 {
didSet {
if UIScreen.main.bounds.maxY == 480 {
constant = 3¨5_insh
}
}
}
@IBInspectable
var 4¨0_insh: CGFloat = 0 {
didSet {
if UIScreen.main.bounds.maxY == 568 {
constant = 4¨0_insh
}
}
}
@IBInspectable
var 4¨7_insh: CGFloat = 0 {
didSet {
if UIScreen.main.bounds.maxY == 667 {
constant = 4¨7_insh
}
}
}
@IBInspectable
var 5¨5_insh: CGFloat = 0 {
didSet {
if UIScreen.main.bounds.maxY == 736 {
constant = 5¨5_insh
}
}
}
}
Don't forgot to inherit your class constraint from ConstraintLayout
I will add the objective-c version soon