在我的项目中,我正在使用自动布局,我在视图控制器上添加了一个或多个标签,为此,我想使用" 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
... etc标签。
答案 0 :(得分:2)
截图
代码
Var myVar = [<the T type>]()
uniq(<some source>, uniqueTitle: &myVar)
func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] {
var buffer = [T]()
var added = Set<T>()
for elem in source {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
//titleatcell is an array with repeating objects.
titleatcell.append(title!)
var uniqueTitle = uniq(titleatcell)
uniqueTitle.append(title!)
print(uniqueTitle)
//return count of objects in array
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = table.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
//Error: uniqueTitle is not declared.
cell.textLabel?.text = uniqueTitle[indexPath.row]
return cell
}
这是功能
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]];