CodeでAutoLayout
CodeでAutoLayout制御
- Viewを中央に表示
// サイズ指定して生成 UILabel *centerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)]; centerLabel.text = @"center"; // Layout制約を決める前にaddSubviewを先にコール [self.view addSubview:centerLabel]; // AutoLayoutを解除して置く centerLabel.translatesAutoresizingMaskIntoConstraints = NO; // Layoutの制約を定義 NSLayoutConstraint *xConstrait = [NSLayoutConstraint constraintWithItem:centerLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]; NSLayoutConstraint *yConstrait = [NSLayoutConstraint constraintWithItem:centerLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]; // 定義した制約を追加 NSArray *constraints = @[xConstrait,yConstrait]; [NSLayoutConstraint activateConstraints:constraints];
- AutoLayoutで画面ごとにsizeを変わるbutton
// サイズ指定せずにボタンを生成 UIButton *closeButton = [[UIButton alloc] init]; // AutoLayoutを無効化 closeButton.translatesAutoresizingMaskIntoConstraints = NO; // buttonの準備 closeButton.backgroundColor = [UIColor blackColor]; [self.view addSubview:closeButton]; // top NSLayoutConstraint *topConstCloseButton = [NSLayoutConstraint constraintWithItem:closeButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:20]; // left NSLayoutConstraint *leftConstCloseButton = [NSLayoutConstraint constraintWithItem:closeButton attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:20]; // bottom NSLayoutConstraint *bottomConstCloseButton = [NSLayoutConstraint constraintWithItem:closeButton attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:-400]; // right NSLayoutConstraint *rightConstCloseButton = [NSLayoutConstraint constraintWithItem:closeButton attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1 constant:-20]; // 制約の追加 NSArray * constArray = @[topConstCloseButton,bottomConstCloseButton,leftConstCloseButton,rightConstCloseButton]; [NSLayoutConstraint activateConstraints:constArray];
bottomとrightはconstantがマイナス値なのに注意!!
ちなみに
制約の追加に
[self.view addConstraints:constraints];
を使うこともできるが
-(void)addConstraint:(NSLayoutConstraint *)constraint NS_AVAILABLE_IOS(6_0); // This method will be deprecated in a future release and should be avoided. Instead, set NSLayoutConstraint's active property to YES.
のように、iOS8~は非推奨になっているので早めに書き換えて置いたほうが良さそう。