自動レイアウトを使用して、UIViewをスーパービューの中央にプログラムで設定するにはどうすればよいですか?
UIButton* viewObj = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[viewObj setTranslatesAutoresizingMaskIntoConstraints:NO];
[viewObj setBackgroundColor:[UIColor greenColor]];
[self.view addSubview:viewObj];
NSLayoutConstraint* cn = [NSLayoutConstraint constraintWithItem:viewObj
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
[self.view addConstraint:cn];
cn = [NSLayoutConstraint constraintWithItem:viewObj
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0];
[self.view addConstraint:cn];
上記のコードはUIButtonで機能しますが、最初の行をUIViewで機能するものに置き換えるのに問題があります。
私はもう試した
UIView* viewObj = [UIView alloc] initWithFrame:CGRectZero];
ただし、ビューはシミュレーターに表示されません。
助言がありますか?
ありがとう!