Как программно установить UILabel только ширину и высоту и ограничения

Я хочу создать UILabel программно с высотой, шириной, а затем я хочу добавить к нему ограничения также программно для позиционирования UILabel.

Обновить:

Я хочу создать такой интерфейс:

введите описание изображения здесь

Как создать этот интерфейс Все программно

Код для создания одной метки label1 Точно так же я создал еще две метки label2 а также label3

UILabel *label1 = [[UILabel alloc]init];

label1.font = TitleFont;
label1.numberOfLines=0;
label1.text= @"Descriptions";
label1.lineBreakMode=NSLineBreakByWordWrapping;
[label1 sizeToFit];
label1.backgroundColor=[UIColor blueColor];
label1.textColor=[UIColor blackColor];
label1.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:label1];

И теперь я могу добавить горизонтальные ограничения с этим кодом

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[label1]-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(label1)]];

Я также могу установить вертикальное ограничение с представлением, но я не могу установить ограничение с одной метки на другую.

3 ответа

Решение

Чтобы создать метку с ограничениями по высоте и ширине, вот ограничения... И не забудьте добавить метку для просмотра с addSubview метод

UILabel *Label = [[UILabel alloc] init];
[Label setTranslatesAutoresizingMaskIntoConstraints:NO];  

[self.view addSubview:Label];

// Width constraint
[Label addConstraint:[NSLayoutConstraint constraintWithItem:Label
                                                      attribute:NSLayoutAttributeWidth
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:nil
                                                      attribute: NSLayoutAttributeNotAnAttribute
                                                     multiplier:1
                                                       constant:200]];

// Height constraint
[Label addConstraint:[NSLayoutConstraint constraintWithItem:Label
                                                      attribute:NSLayoutAttributeHeight
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:nil
                                                      attribute: NSLayoutAttributeNotAnAttribute
                                                     multiplier:1
                                                       constant:21]];

И в Свифте

 Label.setTranslatesAutoresizingMaskIntoConstraints(false)
 self.view.addSubview(Label)

 Label.addConstraint(NSLayoutConstraint(item: Label, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 21))
 Label.addConstraint(NSLayoutConstraint(item: Label, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200))  

Проверьте эту ссылку для более подробной информации

ОБНОВИТЬ
Когда вы обновляете свой вопрос, вот мой обновленный ответ...

UILabel *Label1 = [[UILabel alloc] init];
[Label1 setTranslatesAutoresizingMaskIntoConstraints:NO];
UILabel *Label2 = [[UILabel alloc] init];
[Label2 setTranslatesAutoresizingMaskIntoConstraints:NO];

Label1.text = @"Label1";
Label1.backgroundColor = [UIColor blueColor];
Label2.text = @"Label2";
Label2.backgroundColor = [UIColor redColor];

[self.view addSubview:Label1];
[self.view addSubview:Label2];

// Width constraint
[Label1 addConstraint:[NSLayoutConstraint constraintWithItem:Label1
                                                  attribute:NSLayoutAttributeWidth
                                                  relatedBy:NSLayoutRelationEqual
                                                     toItem:nil
                                                  attribute: NSLayoutAttributeNotAnAttribute
                                                 multiplier:1
                                                   constant:280]];

// Height constraint
[Label1 addConstraint:[NSLayoutConstraint constraintWithItem:Label1
                                                  attribute:NSLayoutAttributeHeight
                                                  relatedBy:NSLayoutRelationEqual
                                                     toItem:nil
                                                  attribute: NSLayoutAttributeNotAnAttribute
                                                 multiplier:1
                                                   constant:21]];

// CenterX constraint
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view
                                                   attribute:NSLayoutAttributeCenterX
                                                   relatedBy:NSLayoutRelationEqual
                                                      toItem:Label1
                                                   attribute: NSLayoutAttributeCenterX
                                                  multiplier:1
                                                    constant:0]];
// Top constraint
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:Label1
                                                      attribute:NSLayoutAttributeTop
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.topLayoutGuide
                                                      attribute: NSLayoutAttributeBottom
                                                     multiplier:1
                                                       constant:40]];


// label2
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:Label1
                                                      attribute:NSLayoutAttributeLeading
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:Label2
                                                      attribute: NSLayoutAttributeLeading
                                                     multiplier:1
                                                       constant:0]];
// label2.Height = label1.Height
[self.view  addConstraint:[NSLayoutConstraint constraintWithItem:Label1
                                                      attribute:NSLayoutAttributeHeight
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:Label2
                                                      attribute: NSLayoutAttributeHeight
                                                     multiplier:1
                                                       constant:0]];
// label2.width = label1.width
[self.view  addConstraint:[NSLayoutConstraint constraintWithItem:Label1
                                                   attribute:NSLayoutAttributeWidth
                                                   relatedBy:NSLayoutRelationEqual
                                                      toItem:Label2
                                                   attribute: NSLayoutAttributeWidth
                                                  multiplier:1
                                                    constant:0]];

// label2.Top
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:Label2
                                                      attribute:NSLayoutAttributeTop
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:Label1
                                                      attribute: NSLayoutAttributeBottom
                                                     multiplier:1
                                                       constant:34]];  

Экран результатов

введите описание изображения здесь

Я пытаюсь этот метод, чтобы изменить высоту как длину текста в вашей метке.

положить viewdidload

[yourlabel setNumberOfLines:0];
    CGRect mainframe = _lbl_board.frame;
    mainframe.size.height =  [self getLabelHeight:yourlabel];
    yourlabel.frame = mainframe;

метод

- (CGFloat)getLabelHeight:(UILabel*)label
{
    CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
    CGSize size;

    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize boundingBox = [label.text boundingRectWithSize:constraint
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:label.font}
                                                  context:context].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

    return size.height;
}

В Swift 3: (просто замените.Hight на.height и.Equal на.equal)

self.addConstraint(NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 35))
Другие вопросы по тегам