我在UIView中有两个按钮,然后我将视图添加到主视图中,但我最终得到了这样的结果:
正如您所看到的,这两个按钮超出了红色视图。
我想要一点保证金,所以我使用constraintsWithVisualFormat:@"V:|-100-[buttonGroup]-10-|"
,我不确定这是否重要。
这是原始代码:
- (UIButton*) getButtonWithTitle: (NSString*) title
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.layer.borderColor = [UIColor blackColor].CGColor;
button.layer.borderWidth = 0.5f;
button.layer.cornerRadius = 2.0f;
[button setTranslatesAutoresizingMaskIntoConstraints:NO];
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState: UIControlStateNormal];
return button;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
UIButton *loginBtn = [self getButtonWithTitle:@"Login"];
UIButton *registerBtn = [self getButtonWithTitle:@"Register"];
UIView *buttonGroup = [[UIView alloc] init];
[buttonGroup setTranslatesAutoresizingMaskIntoConstraints:NO];
[buttonGroup addSubview: loginBtn];
[buttonGroup addSubview: registerBtn];
[self.view addSubview: buttonGroup];
[buttonGroup setBackgroundColor:[UIColor redColor]];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(loginBtn, registerBtn, buttonGroup);
[buttonGroup addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[loginBtn]-20-[registerBtn(==loginBtn)]-|"
options:0
metrics:nil
views:viewsDictionary
]];
NSArray *verticalConstraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-100-[buttonGroup]-10-|"
options:0
metrics:nil
views:viewsDictionary];
NSArray *horizontalConstraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"H:|-[buttonGroup]-|"
options:0
metrics:nil
views:viewsDictionary];
[self.view addConstraints: horizontalConstraints];
[self.view addConstraints: verticalConstraints];
}
修改
我添加的限制:
[buttonGroup addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[loginBtn]-|"
options:0
metrics:nil
views:viewsDictionary
]];
[buttonGroup addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[registerBtn]-|"
options:0
metrics:nil
views:viewsDictionary
]];
看起来我做了额外的工作......
答案 0 :(得分:1)
您从未在按钮和buttonGroup之间创建任何垂直约束;添加那些,你应该是好的。此外,您不应将控制器的self.view的translatesAutoresizingMaskIntoConstraints设置为NO(仅适用于您添加到其中的子视图)。
答案 1 :(得分:1)
在VFL中,|表示超级视图,但是您的两个按钮(loginBtn,registerBtn)是buttonGroup的子视图。因此,您应该使用buttonGroup定义有关loginBtn,registerBtn的V关系。正如rdelmar所说,self.view应该将translatesAutoresizingMaskIntoConstraints设置为No.这可以关闭autosizingmask函数。我认为在xib或storyboard中做这件事的最好方法。