gpt4 book ai didi

ios - 我们如何使用自动布局在 for 循环的帮助下创建 UIlabel?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:02 27 4
gpt4 key购买 nike

在我的项目中,我使用了自动布局,并且在我的 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 循环中插入 nameTextFieldemailTextField...等标签。

最佳答案

截图

代码

 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 *)createLabelWithText:(NSString *)text{
UILabel * label = [[UILabel alloc] init];
label.text = text;
label.textColor = [UIColor blackColor];
label.translatesAutoresizingMaskIntoConstraints = NO;
return label;
}

关于ios - 我们如何使用自动布局在 for 循环的帮助下创建 UIlabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33206481/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com