Я хочу использовать автозапуск, чтобы центрировать изображение по вертикали и по горизонтали, но как-то у меня возникают проблемы. Я работаю на iOS8-симуляторе и устройстве iOS8. Есть две версии кода, которые я пробовал, и никто из них не работает. Ниже приведены фрагменты кода:Программно автоотключение не центрируется по вертикали
Сначала давайте выделить вид, что мы используем:
UIView *inputView = UIView.new; //Don't hate me for the dot syntax :)
inputView.translatesAutoresizingMaskIntoConstraints = NO;
inputView.backgroundColor = UIColor.redColor;
[self.view addSubview:inputView];
Попытка # 1:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:inputView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]; //Center the view horizontally
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:inputView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]; //And make it have the same width as the view
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:inputView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0f constant:260.0f]; //Force exactly 260pts view height
[inputView addConstraint:constraint]; //If I add it to self.view it's the same thing
constraint = [NSLayoutConstraint constraintWithItem:inputView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:0.5f constant:0.0f]; //And try to center it vertically - DOES NOT WORK... wtf
[self.view addConstraint:constraint];
Кажется совершенно законный кусок кода для меня. Но НОПЕ.
Попытка №2. Это в основном то же самое с меньшим количеством строк кода.
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-[inputView(>=320)]-|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:NSDictionaryOfVariableBindings(inputView)];
[self.view addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[inputView(260)]-|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:NSDictionaryOfVariableBindings(inputView)];
[self.view addConstraints:constraints];
Теперь этот тоже не работает. Я имею в виду, что центр горизонтали горизонтально, но когда я добавляю вертикальное ограничение, я получаю предупреждение, говорящее мне, что я сосать авто макет. В нем говорится, что он не может удовлетворить все ограничения. А именно:
(
"<NSLayoutConstraint:0x17408be00 UIView:0x174197010.top == UIView:0x174196da0.topMargin>",
"<NSLayoutConstraint:0x17408bdb0 V:[UIView:0x174197010(260)]>",
"<NSLayoutConstraint:0x17408bd60 UIView:0x174196da0.bottomMargin == UIView:0x174197010.bottom>",
"<NSLayoutConstraint:0x17008a000 'UIView-Encapsulated-Layout-Height' V:[UIView:0x174196da0(667)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x17408bd60 UIView:0x174196da0.bottomMargin == UIView:0x174197010.bottom>
Я не уверен, как это исправить. Ниже приведены фотографии результатов, которые я получаю от попыток №1 и №2.
Как я могу это исправить?
lol с синтаксисом точки. позвольте мне угадать: ваше расширение UIView называется UIView + Swift! – user2320861
Нет, это на самом деле все ObjC :) Это была очень хромая вещь, появившаяся Apple давно, я думаю. Он не отображается в завершении синтаксиса, но, тем не менее, компилируется. Попробуйте. Если найти его чище, чем '[UIView new]'. – Majster