LoginSignup
11
10

More than 5 years have passed since last update.

Auto Layout で端末サイズに応じた View のサイズ調整

Last updated at Posted at 2015-02-07

やりたかったこと

Storyborad + Auto Layout による画面設計をしていて、とある View の高さを、iPhone5, iPhone6, iPhone6 Plus でそれぞれ 50, 100, 100 といったように変えたかった。

端末種別を区別する

下記のようなメソッドを用意して、戻り値によって端末サイズを判断する。
下記メソッドの場合、iPhone5, iPhone6, iPhone6 plus でそれぞれ、320, 375, 414 が返ってくる。

func getScreenWidth() -> CGFloat {
    let screenSize = UIScreen.mainScreen().bounds
    return screenSize.width
}

参考
http://stackoverflow.com/questions/24110762/swift-determine-ios-screen-size

制約をつける

Storyboard 上で高さに関する制約を削除し、プログラム内で対象の View に制約を追加する。

let height: CGFloat = 50

let constraint = NSLayoutConstraint(
    item: self.targetView,
    attribute: NSLayoutAttribute.Height,
    relatedBy: NSLayoutRelation.Equal,
    toItem: nil,
    attribute: NSLayoutAttribute.NotAnAttribute,
    multiplier: 1,
    constant: height)

self.targetView.addConstraint(constraint)

参考
http://stackoverflow.com/questions/26180822/swift-adding-constraints-programmatically

11
10
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
11
10