Подтвердить что ты не робот

Программно программно обновить ограничение по высоте

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

[[self view] addConstraint:[NSLayoutConstraint constraintWithItem:loginContainer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:loginFrame.size.height]];

В консоли отображается

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]>",
    "<NSLayoutConstraint:0x787da210 V:[UIView:0x790cdfb0(400)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
4b9b3361

Ответ 1

Вместо добавления нового ограничения вам необходимо изменить константу в существующем ограничении.

Используйте IBOutlet для подключения к вашему ограничению в Interface Builder:

@property (nonatomic, weak) NSLayoutConstraint *heightConstraint;

Затем, когда вам нужно установить его программным путем, просто установите для свойства константы ограничение:

heightConstraint.constant = 100;

ИЛИ

Если вы не можете получить доступ к nib в Interface Builder, найдите ограничение в коде:

NSLayoutConstraint *heightConstraint;
for (NSLayoutConstraint *constraint in myView.constraints) {
    if (constraint.firstAttribute == NSLayoutAttributeHeight) {
        heightConstraint = constraint;
        break;
    }
}
heightConstraint.constant = 100;

И в Swift:

if let constraint = (myView.constraints.filter{$0.firstAttribute == .width}.first) {
            constraint.constant = 100.0
        }

Ответ 2

Чтобы получить ссылку на ваши ограничения по высоте: Нажмите Ctrl + Ctrl и перетащите в свой файл класса:

enter image description here

Чтобы обновить значение ограничения:

self.heightConstraint.constant = 300;
[self.view updateConstraints];

Ответ 3

Позвоните в свой вид nibView. Таким образом, вы пытаетесь загрузить это представление в контроллере представления, поэтому, во-первых, в вашем контроллере просмотра вам нужно загрузить его, как вы это делаете, с помощью

[[NSBundle mainBundle] loadNibNamed:@"NibView" owner:self options:nil];

Затем вам нужно сообщить nibView, что он вам не нужен, чтобы преобразовать маски авторезинирования в ограничения, выполнив

nibView.translatesAutoresizingMaskIntoConstraints = NO;

Затем вы можете добавить свои ограничения

    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:nibView
                                                                                  attribute:NSLayoutAttributeHeight
                                                                                  relatedBy:NSLayoutRelationEqual
                                                                                     toItem:nil
                                                                                  attribute:NSLayoutAttributeNotAnAttribute
                                                                                 multiplier:1.0
                                                                                   constant:yourValue];

И, наконец, просто добавьте его в ограничения вида:

[self.view addConstraint:heightConstraint];

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