やりたかったこと
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