LoginSignup
1
5

More than 5 years have passed since last update.

【swift】AutoLayoutのConstraintで端末毎のサイズを変更する

Last updated at Posted at 2018-09-18

storyboardのautolayoutを使った場合に、端末毎のサイズは画面サイズから比率で表示させる等をしなければなりませんが、NSLayoutConstraintを継承したクラスを作成してgetter,setterを設定することで、端末毎に対応したNSLayoutConstraintを利用することが出来ます。

Setting.swift
// 基準とする画面縦幅
let baseScreenHeight: CGFloat = 667.0
// 基準とする画面横幅
let baseScreenWidth: CGFloat = 375.0

// 端末サイズ計算 (Height)
func calculateDeviceHeightSize(_ values: CGFloat) -> CGFloat {
    // iPhoneXの場合は、iPhone6の基準に合わす
    if UIScreen.main.bounds.size.height == 812.0 {
        return values
    }
    return values * UIScreen.main.bounds.size.height / baseScreenHeight
}
// 端末サイズ計算 (Width)
func calculateDeviceWidthSize(_ values: CGFloat) -> CGFloat {
    return values * UIScreen.main.bounds.size.width / baseScreenWidth
}
CustomConstraint.swift
/**
 Constraintを端末サイズ毎に変更するカスタムクラス
 横方向のサイズに利用
 */
class CustomConstraintWidth: NSLayoutConstraint {
    override var constant: CGFloat {
        get {
            return calculateDeviceWidthSize(super.constant)
        }
        set {
            super.constant = newValue
        }
    }
}

/**
 Constraintを端末サイズ毎に変更するカスタムクラス
 縦方向のサイズに利用
 */
class CustomConstraintHeight: NSLayoutConstraint {
    override var constant: CGFloat {
        get {
            return calculateDeviceHeightSize(super.constant)
        }
        set {
            super.constant = newValue
        }
    }
}

storyboardで設定する場合は、以下のようにCustom Classを設定します。

CustomConstraint.png

StackViewのspacingを端末サイズ毎に変更する場合は、こちらになります。

CustomSpacingStackView.swift
/**
 StackViewのspacingを端末サイズ毎に変更するカスタムクラス
 */
class CustomSpacingStackView: UIStackView {
    override var spacing: CGFloat {
        get {
            return super.spacing
        }
        set {
            if axis == .horizontal {
                super.spacing = calculateDeviceWidthSize(newValue)
            } else {
                super.spacing = calculateDeviceHeightSize(newValue)
            }
        }
    }
}
1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5