程序化居中自动布局不起作用

时间:2015-01-04 05:49:30

标签: objective-c cocoa autolayout center

有一个名为parentView的视图;我想把它放在superview的中心。代码如下。

当我添加代码并编译时,没有什么不同 - 代码没有效果?

NSDictionary *viewsDictionary=@{@"parentView":_parentView};

[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
[_parentView setTranslatesAutoresizingMaskIntoConstraints:NO];

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[parentView(==200)]" options:0 metrics:nil views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[parentView(==222)]" options:0 metrics:nil views:viewsDictionary]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_parentView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_parentView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0]];

1 个答案:

答案 0 :(得分:0)

您可以尝试在开头插入以下行,我假设parentView是故事板中定义为IBOutlet的视图。

[self.view removeConstraints:self.view.constraints];