我的UITableView
UITableViewCells
包含UITextfield
,但是当我在其他设备上测试时,它没有任何约束。我希望它坚持UITableViewCell
的右侧,如何以编程方式添加?
nameField.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *constraint2 = [NSLayoutConstraint constraintWithItem:nameField attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
[nameField addConstraint:constraint2];
[cell.contentView addSubview:nameField];
答案 0 :(得分:0)
我希望它对你有帮助。 //你可以在右侧设置UITextField对齐
UITextField *nameField = [[UITextField alloc] initWithFrame:CGRectMake(120, 8, 185, 30)];
nameField.adjustsFontSizeToFitWidth = YES;
[nameField setFont:[UIFont fontWithName:@"Roboto-Regular" size:15]];
[nameField setUserInteractionEnabled:NO];
[nameField setDelegate:self];
[nameField setTextColor:[UIColor lightGrayColor]];
cell.textLabel.text = @"Server Name";
[nameField setUserInteractionEnabled:YES];
nameField.textAlignment=NSTextAlignmentRight; // you can set right alignment
nameField.text = [serverInfo valueForKey:@"name"];
[textFields addObject:nameField];
[cell.contentView addSubview:nameField];
答案 1 :(得分:0)
尝试使用以下代码(用您的字段替换我的字段)。我使用它来居中我的文本视图,但我更改了水平约束,所以它右对齐它。
cell = [tableView dequeueReusableCellWithIdentifier:@"yourCustomCell"];
[[cell.contentView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
UILabel *myLabel = [[UILabel alloc]init];
myLabel.text = @"Detail";
//Create your text view here
[cell.contentView addSubview:myLabel];
[cell.contentView addSubview:nameField];
myLabel.translatesAutoresizingMaskIntoConstraints = NO;
nameField.translatesAutoresizingMaskIntoConstraints = NO;
NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:3];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(myLabel, nameField);
NSString *verForName = [NSString stringWithFormat:@"V:|[nameField]|"];
NSString *verForLabel = [NSString stringWithFormat:@"V:|[myLabel]|"];
NSString *horForView = [NSString stringWithFormat:@"H:|[myLabel]->=1-[nameField]-15-|"];
[result addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:verForLabel options:0 metrics:nil views:viewsDictionary]];
[result addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:verForName options:0 metrics:nil views:viewsDictionary]];
[result addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:horForView options:0 metrics:nil views:viewsDictionary]];
[cell.contentView addConstraints:result]; }
答案 2 :(得分:0)
尝试添加以下内容:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:nameField attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeRight multiplier:1.0 constant:0]
[textField addConstraint:constraint];
免责声明:在这个文本编辑器中这一切都是为了答案,所以它可能在语法上不正确,但这是一般的想法。如果您需要任何帮助,请告诉我们!
答案 3 :(得分:0)
如果您正在进行自动布局,则缺少display: block;
。
之后你只需创建一个constrint:
nameField.translatesAutoresizingMaskIntoConstraints = NO;
和尺寸的约束 - 高度和宽度。