我正在尝试学习视觉格式语言,在这种情况下,我希望视图顶部的两个按钮彼此相邻。
这是我的代码但没有出现?
UIButton *button1 = [[UIButton alloc] init];
[button1 setBackgroundColor:[UIColor blueColor]];
UIButton *button2 = [[UIButton alloc] init];
[button2 setBackgroundColor:[UIColor redColor]];
NSDictionary *views = NSDictionaryOfVariableBindings(button1, button2);
NSLog(@"%@", [views allKeys]);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"[button1(==button2)]" options:0 metrics:Nil views:views];
[self.view addSubview:button1];
[self.view addSubview:button2];
[self.view addConstraints:constraints];
感谢答案,现在是我的代码:
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
button1.translatesAutoresizingMaskIntoConstraints = NO;
[button1 setTitle:@"Button" forState:UIControlStateNormal];
[button1 setBackgroundColor:[UIColor redColor]];
[self.view addSubview:button1];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
button2.translatesAutoresizingMaskIntoConstraints = NO;
[button2 setTitle:@"Button" forState:UIControlStateNormal];
[button2 setBackgroundColor:[UIColor blueColor]];
[self.view addSubview:button2];
NSDictionary *views = NSDictionaryOfVariableBindings(button1, button2);
NSString *const kHConstraint = @"|-[button1(==button2)]-[button2]-|";
NSString *const kVConstraint = @"V:|-[button1(==44)]";
NSString *const kVConstraint2 = @"V:|-[button2(==44)]";
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:kHConstraint options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:kVConstraint options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:kVConstraint2 options:0 metrics:nil views:views]];
如果我可以将两个垂直约束合并为一个,我会徘徊吗?
是的,可以使用选项NSLayoutFormatAlignAllTop:
NSDictionary *views = NSDictionaryOfVariableBindings(button1, button2);
NSString *const kHConstraint = @"H:|-[button1(==button2)]-[button2]-|";
NSString *const kVConstraint = @"V:|-[button1(==button2)]";
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:kHConstraint options:NSLayoutFormatAlignAllTop metrics:metrics views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:kVConstraint options:0 metrics:metrics views:views]];
来自:@jrturton的精彩文章,可以找到here
答案 0 :(得分:3)
您需要为两个按钮关闭自动调整功能:
button1.translatesAutoresizingMaskIntoConstraints = NO;
button2.translatesAutoresizingMaskIntoConstraints = NO;
您必须为系统指定足够的约束,以确定每个子视图的高度,宽度和位置。否则默认帧为CGRectZero
,它将不可见。
至少,我建议以下VFL语句为您提供所需的布局:
@"V:|-[button1(==44)]"
这使你的button1高度为44,并将其从superview顶部定位为标准插入。
@"V:|[button2(==44)]"
这与按钮2的作用相同。您也可以通过水平布局中的对齐选项来实现此目的,但这会使问题混淆。
@"|-[button1(==button2)]-[button2]-|"
这使得按钮的宽度相等,并且还将它们与superview的边缘相连。
我已经写了很长篇here的VFL,希望能帮助你理解。