woshidan's loose leaf

ぼんやり勉強しています

UIImageViewはデフォルトだと正方形になるのとNSConstraintは親Viewに対して親Viewと子Viewないし子View同士の関係を指定する

  • NSConstraintは親Viewに対して親Viewと子Viewないし子View同士の関係を指定する
    • これが独学Androiderに理解できなくて理解できた瞬間うぉぉたぁああって感じだった
  • UIImageViewはデフォルトだと translatesAutoresizingMaskIntoConstraints = YES
    • AutoresizingMaskAutoLayout 以前の指定方法で、このオプションが YES だと AutoLayout の制約以外に余計な制約がかかっている状態なので、あれ? AutoLayout動いてないなってなる
    • UIImageViewは上記オプションなしでConstraint追加なしだと正方形になるので、画像のアスペクト比になるように指定を追加してやる
    • http://crossbridge-lab.hatenablog.com/entry/2016/02/29/125917
  • Constraintの初期化、書くの長いなって思った時、AndroidのレイアウトリソースぐらいのノリでConstraint作るメソッド書いたらかなり読みやすくなった
    • 要素の有無自体をどうこうしたい場合、Storyboardよりコードの方がやりやすいイメージなんですがあまり経験がないので不明
    • iOS6とかを捨てて、Swiftに移行する方が世界の流れとして正しいが、toBだと簡単に下位バージョンがきれないんじゃ
    • 仕様の把握がてら一旦ボトムアップ的なこういう整理の段階挟むのはありかなと思っているけどどうなんでしょ

Before

[constraints addObjectsFromArray:@[
    [NSLayoutConstraint constraintWithItem:childView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0],
    [NSLayoutConstraint constraintWithItem:childView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0],
    [NSLayoutConstraint constraintWithItem:childView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1 constant:to:targetWidth]
]];

After

[constraints addObjectsFromArray:@[[self constraintToAlignCenterXOf:childView with:self.view],
                                   [self constraintToAlignCenterYOf:childView with:self.view],
                                   [self constraintToSetWidthOf:childView to:targetWidth]]];