In my project I am using auto-layouts and I am adding one or more labels on my view-controller and for this I would like to use a "for" loop by means of code reducing purpose but using "constraintWithVisualFormate".
I do not understand!
How can I use a for loop?
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]];
}
I am struggling near above for loop because I am not understand how can we insert nameTextField
, emailTextField
...etc labels inside for loop.
Screenshot
Code
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]];
This is the function
-(UILabel *)createLabelWithText:(NSString *)text{
UILabel * label = [[UILabel alloc] init];
label.text = text;
label.textColor = [UIColor blackColor];
label.translatesAutoresizingMaskIntoConstraints = NO;
return label;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.