在我的项目中,我使用了自动布局,并在我的 View Controller 上添加了一个或多个标签,为此我想通过代码减少的目的使用“for”循环,但使用“constraintWithVisualFormate”。
我不明白!
如何使用 for 循环?
emailTextField = [[UILabel alloc] init];
emailTextField.text = @"MD (Medician)";
emailTextField.textColor = [UIColor blackColor];
emailTextField.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview: emailTextField];
nameTextField = [[UILabel alloc] init];
nameTextField.text = @"Experience:12 Years";
nameTextField.textColor = [UIColor blackColor];
nameTextField.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview: nameTextField];
password = [[UILabel alloc] init];
password.text = @"Experience:12 Years";
password.textColor = [UIColor blackColor];
password.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview: password];
//Applying auto-layouts for labels
NSDictionary * views = NSDictionaryOfVariableBindings(emailTextField,nameTextField,password);
NSArray *textFields = @[emailTextField, nameTextField, password];
for (UITextField *textField in textFields) {
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat"H:|-10-[textField]-10-|"
options:0
metrics:nil
views:viewsDic]];
}
我在上面的 for 循环附近苦苦挣扎,因为我不明白如何在 for 循环中插入 nameTextField
、emailTextField
...等标签。
截图
代码
emailTextField = [self createLabelWithText: @"MD (Medician)"];
[self.view addSubview: emailTextField];
nameTextField = [self createLabelWithText: @"Experience:12 Years"];
[self.view addSubview: nameTextField];
passwword = [self createLabelWithText: @"Experience:12 Years"];
[self.view addSubview: passwword];
NSDictionary * viewsDic = NSDictionaryOfVariableBindings(emailTextField,nameTextField,passwword);
NSArray * keys = @[@"emailTextField",@"nameTextField",@"passwword"];
for (NSString * key in keys) {
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat"H:|-10-[%@]-10-|",key]
options:0
metrics:nil
views:viewsDic]];
}
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat"V:|-20-[emailTextField]-[nameTextField]-[passwword]"
options:0
metrics:nil
views:viewsDic]];
这是函数
-(UILabel *)createLabelWithTextNSString *)text{
UILabel * label = [[UILabel alloc] init];
label.text = text;
label.textColor = [UIColor blackColor];
label.translatesAutoresizingMaskIntoConstraints = NO;
return label;
}
关于ios - 我们如何使用自动布局在 for 循环的帮助下创建 UIlabels?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33206481/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |