2
我想學習可視化格式語言,在這種情況下,我想在視圖的頂部相鄰的兩個按鈕。iOS的VFL顯示兩個按鈕nextother
這是我的代碼,但沒有顯示?
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
謝謝修復,並學到更多。肯定會閱讀你的文章 – Haagenti