LoginSignup
4
4

More than 5 years have passed since last update.

autolayout + コード

Posted at

autolayoutやっと勉強使い始めたけど、コードでViewを変更するときに苦労したからまとめ

①frameで変更出来ない

view.frame = CGRectMake(0.0, 0.0, 100.0, 200.0);
ッて感じでコードしてい変形してた所
数字をどうするかは別途置いといてこうゆう場合は
objc:sample
view.translatesAutoresizingMaskIntoConstraints = YES;
view.frame = CGRectMake(0.0, 0.0, 100.0, 200.0);

って感じで「translatesAutoresizingMaskIntoConstraints」でオートレイアウト状態を解除する必要があります。

②コードでautolayout変更したい

で次にどーせなんだからコードでオートレイアウトしようとqiitaで調べると
コードでAutolayout
とかあるんですがこれだとやりたかったことには足りなくて
やりたかったこととしては回転による制約の付け替え
ってのがあって、制約は一度つけるそのままaddしても増えない。
かつ調べる内に上のやり方は準非推奨みたいな非推奨だけどまだ線はひかれてない?
iOS8でコードでのAutoLayoutのやり方が地味に変わっていた件
- addConstraints: Reference
ッて感じで公式みても8.0でなんとかかんとか書いてありますね。
ってことで正解としてはたぶん
objc:sample
NSArray *constraints;
// 制約の解除
[NSLayoutConstraint deactivateConstraints:constraints];
// 制約の作成
constraints = @[
[NSLayoutConstraint constraintWithItem:_greenView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:_bgView
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0],
[NSLayoutConstraint constraintWithItem:_greenView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:_bgView
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:0.0]
];
// 制約の設定
[NSLayoutConstraint activateConstraints:constraints];

ッて感じの流れになる。

デフォルトの制約は邪魔

後outletで設定してるものをコード制約でやりたい場合は
スクリーンショット 2015-11-02 1.48.47.png
って感じで
「Remove at build time」
を設定する必要がある。
 ※すみません、参考にしたサイト忘れました。
制約つけとかないとエラーマークでちゃうからこれなんだろうな〜

☆まとめ
 コードで変更する場合は
 ①オートレイアウトを解除してframeで変更
 ②オートレイアウトで変更(付けかえ、「Remove at build time」意識)
ッて感じでやる必要があるっぽい。
他にもあるとは思うけど。

4
4
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
4
4