這裏有一個解決方案(應該去-viewDidLoad
)。有幾件事值得注意:
首先,VFL不允許您創建所有可能的約束類型。特別是,需要使用+constraintWithItem:
類方法在NSLayoutConstraint
上進行對中。其次,如註釋中所述,您可以在水平VFL字符串中使用硬編碼的左右pad值來實現居中,但如果您需要支持不同的設備大小,則可能會導致問題。
第三,撥打-setTranslatesAutoresizingMaskIntoConstraints:
是至關重要的。如果您忘記了這一點,Programmatic Autolayout將完全失效。此外,你需要確保所有的意見設置限制之前被添加到他們的superviews,否則任何約束字符串引用上海華盈會導致崩潰
NSArray *names = @[@"button1",@"button2",@"button3"];
NSMutableDictionary *views = [[NSMutableDictionary alloc]init];
for(NSUInteger i=0;i<3;i++) {
UIButton *b = [[UIButton alloc]init];
NSString *name = names[i];
[b setTitle:name forState:UIControlStateNormal];
views[name] = b;
[b setBackgroundColor:[UIColor redColor]];
[b setTranslatesAutoresizingMaskIntoConstraints:false];
[self.view addSubview:b];
}
//List of values to be used in the constraints
NSDictionary *metrics = @{
@"buttonWidth":@150,
@"bHeight":@50, //button height
@"topPad":@100,
@"vPad":@20 //vertical padding
};
//Horizontal VFL string (repeated for all rows).
for (NSString *buttonName in views.allKeys) {
NSString *horizontalConstraintString = [NSString stringWithFormat:@"|-(>=0)-[%@(buttonWidth)]-(>=0)-|",buttonName];
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:horizontalConstraintString options:0 metrics:metrics views:views];
[self.view addConstraints:horizontalConstraints];
//Can't do centering with VFL - have to use constructor instead. You could also hardcode left and right padding in the VFL string above, but this will make it harder to deal with different screen sizes
NSLayoutConstraint *centerConstraint = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:views[buttonName] attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
[self.view addConstraint:centerConstraint];
}
//Vertical VFL (vertical spacing of all buttons)
NSString *verticalConstraintString = @"V:|-topPad-[button1(bHeight)]-vPad-[button2(bHeight)]-vPad-[button3(bHeight)]-(>=0)-|";
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:verticalConstraintString options:0 metrics:metrics views:views];
[self.view addConstraints:verticalConstraints];
[self.view layoutIfNeeded];
謝謝豐富託利現在我明白了。你能否提供鏈接,我可以更詳細地瞭解? –