Добавление ограничений программно - PullRequest
0 голосов
/ 06 ноября 2018

Я пытаюсь получить следующую компоновку программно:

enter image description here

Это подкласс UIView, на котором я хотел бы разместить UILabel с фиксированной высотой (40 пикселей), динамической шириной (ширина рассчитывается на основе длины текста, поэтому я думаю, что это можно считать фиксированной, а не динамический, потому что я вычисляю его только один раз) и ровно 40 пикселей слева и снизу.

Вот мой код:

- (UIView *) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {

    marginGeneral       = 40.0f;

    UILabel *titleLabel = [[UILabel alloc] init];
    [titleLabel setTranslatesAutoresizingMaskIntoConstraints: NO];
    titleLabel.backgroundColor  = [UIColor blackColor];
    titleLabel.textColor        = [UIColor whiteColor];
    titleLabel.text             = @"Some Text";
    [self addSubview:titleLabel];

    NSLayoutConstraint *contsTitleLeft = [NSLayoutConstraint
                                          constraintWithItem: titleLabel
                                          attribute: NSLayoutAttributeLeft
                                          relatedBy: NSLayoutRelationEqual
                                          toItem: self
                                          attribute: NSLayoutAttributeLeft
                                          multiplier: 1.0
                                          constant: marginGeneral];

    NSLayoutConstraint *contsTitleRight = [NSLayoutConstraint
                                           constraintWithItem: titleLabel
                                           attribute: NSLayoutAttributeRight
                                           relatedBy: NSLayoutRelationEqual
                                           toItem: self
                                           attribute: NSLayoutAttributeRight
                                           multiplier: 1.0
                                           constant: marginGeneral * -1.0f];

    NSLayoutConstraint *contsTitleBottom = [NSLayoutConstraint
                                            constraintWithItem: titleLabel
                                            attribute: NSLayoutAttributeBottom
                                            relatedBy: NSLayoutRelationEqual
                                            toItem: self
                                            attribute: NSLayoutAttributeBottom
                                            multiplier: 1.0
                                            constant: marginGeneral * -1.0f];

    NSLayoutConstraint *contsTitleHeight = [NSLayoutConstraint
                                            constraintWithItem: titleLabel
                                            attribute: NSLayoutAttributeHeight
                                            relatedBy: NSLayoutRelationEqual
                                            toItem: nil
                                            attribute: NSLayoutAttributeNotAnAttribute
                                            multiplier: 1.0
                                            constant: 40.0f];

    [self addConstraints:@[contsTitleLeft, contsTitleRight, contsTitleBottom]];
    [titleLabel addConstraint:contsTitleHeight];

    }

return self;
}

@end

Это, конечно, возвращает все виды предупреждений, связанных с ограничениями, и метка не отображается.

Не могли бы вы, милые люди, помочь мне понять, где я ошибся и как это исправить? Большое спасибо!

P.s .: Я не использую конструктор интерфейса, так что это не вариант. :)

1 Ответ

0 голосов
/ 06 ноября 2018

Прежде всего, вы никогда не добавляли titleLabel в качестве подпредставления.

Во-вторых, вам нужно игнорировать маски авторазмера, чтобы избежать конфликтов в ограничениях.

В-третьих, вы добавляете ограничение высоты для просмотра, тогда как оно принадлежит метке.

Вот код, который работает:

UILabel *titleLabel = [[UILabel alloc] init];
[titleLabel setTranslatesAutoresizingMaskIntoConstraints: NO];
titleLabel.backgroundColor  = [UIColor blackColor];
titleLabel.textColor        = [UIColor whiteColor];
titleLabel.text             = @"Some Text";
[self.view addSubview: titleLabel];

NSLayoutConstraint *contsTitleLeft = [NSLayoutConstraint
                                      constraintWithItem: titleLabel
                                      attribute: NSLayoutAttributeLeft
                                      relatedBy: NSLayoutRelationEqual
                                      toItem: self
                                      attribute: NSLayoutAttributeLeft
                                      multiplier: 1.0
                                      constant: marginGeneral];

NSLayoutConstraint *contsTitleRight = [NSLayoutConstraint
                                       constraintWithItem: titleLabel
                                       attribute: NSLayoutAttributeRight
                                       relatedBy: NSLayoutRelationEqual
                                       toItem: self
                                       attribute: NSLayoutAttributeRight
                                       multiplier: 1.0
                                       constant: marginGeneral * -1.0f];

NSLayoutConstraint *contsTitleBottom = [NSLayoutConstraint
                                        constraintWithItem: titleLabel
                                        attribute: NSLayoutAttributeBottom
                                        relatedBy: NSLayoutRelationEqual
                                        toItem: self
                                        attribute: NSLayoutAttributeBottom
                                        multiplier: 1.0
                                        constant: marginGeneral * -1.0f];

NSLayoutConstraint *contsTitleHeight = [NSLayoutConstraint
                                        constraintWithItem: titleLabel
                                        attribute: NSLayoutAttributeHeight
                                        relatedBy: NSLayoutRelationEqual
                                        toItem: nil
                                        attribute: NSLayoutAttributeNotAnAttribute
                                        multiplier: 1.0
                                        constant: 40.0f];

[self addConstraints:@[contsTitleLeft, contsTitleRight, contsTitleBottom]];
[titleLabel addConstraint: contsTitleHeight];

UPD: Добавление пользовательского вида для просмотра контроллера в viewDidLoad:

CustomView *customView = [[CustomView alloc] initWithFrame: CGRectMake(0, 0, 200, 200)];
[customView setTranslatesAutoresizingMaskIntoConstraints: NO];
[customView setBackgroundColor: [UIColor greenColor]];
[self.view addSubview: customView];

NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem: customView
                                                                       attribute: NSLayoutAttributeWidth
                                                                       relatedBy: NSLayoutRelationEqual
                                                                          toItem: nil
                                                                       attribute: NSLayoutAttributeNotAnAttribute
                                                                      multiplier:1
                                                                        constant:200];
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem: customView
                                                                       attribute: NSLayoutAttributeHeight
                                                                       relatedBy: NSLayoutRelationEqual
                                                                          toItem: nil
                                                                       attribute: NSLayoutAttributeNotAnAttribute
                                                                      multiplier:1
                                                                        constant:200];

[customView addConstraints: @[widthConstraint, heightConstraint]];

NSLayoutConstraint *centerHorizontallyConstraint = [NSLayoutConstraint constraintWithItem: customView
                                                                                    attribute: NSLayoutAttributeCenterX
                                                                                    relatedBy: NSLayoutRelationEqual
                                                                                       toItem: self.view
                                                                                    attribute: NSLayoutAttributeCenterX
                                                                                   multiplier: 1
                                                                                     constant: 0];

NSLayoutConstraint *centerVerticallyConstraint = [NSLayoutConstraint constraintWithItem: customView
                                                                                    attribute: NSLayoutAttributeCenterY
                                                                                    relatedBy: NSLayoutRelationEqual
                                                                                       toItem: self.view
                                                                                    attribute: NSLayoutAttributeCenterY
                                                                                   multiplier: 1
                                                                                     constant: 0];

[self.view addConstraints: @[centerHorizontallyConstraint, centerVerticallyConstraint]];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...