0

Я создаю настраиваемое представление, которое необходимо добавить в качестве подзадачи в UIWindow. Я правильно настроил ограничения для его подвью, но я смущен, когда/как устанавливать ограничения на представление по отношению к окну.Autolayout при добавлении subview в UIWindow

Я хотел бы, чтобы ширина предупреждения была равна 70% от ширины экрана. Высота уже относится к ее подзонам.

- (void)show { 
UIWindow *window = [[UIApplication sharedApplication] keyWindow]; 
[window addSubview:self]; 

[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:[UIApplication sharedApplication].keyWindow attribute:NSLayoutAttributeWidth multiplier:0.7 constant:0]];   
[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_messageLabel attribute:NSLayoutAttributeBottom multiplier:1.0 constant:10]]; 
[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:(_imageView.image ? _imageView : _titleLabel) attribute:NSLayoutAttributeTop multiplier:1.0 constant:-10]]; 

} 

Что я делаю неправильно? Я получаю следующее сообщение об ошибке:

NSLayoutConstraint:0x181cd7c0 WFSoftAlertView:0x16e384c0.width == 0.7*UIWindow:0x16e7c8c0.width> 
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. 

ответ

1

Попробуйте изменить constraintWithItem от себя к self.view

3
WFSoftAlertView.translatesAutoresizingMaskIntoConstraints=NO; 
NSDictionary *views = NSDictionaryOfVariableBindings(WFSoftAlertView); 
float width30 = self.view.frame.size.width*.3; 
width30 = width30/2; // divided by 2 for padding of its left/rigth 
NSString *str =[NSString stringWithFormat:@"%f",width30]; 
NSDictionary *metrics = @{@"width":str}; 

[self.view addSubview:WFSoftAlertView]; 
//add the WFSoftAlertView in center(x) of superview with a padding of "width" 
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-width-[WFSoftAlertView]-width-|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:metrics views:views]]; 

// if you want center(y) 
NSLayoutConstraint *centerY = [NSLayoutConstraint 
          constraintWithItem:WFSoftAlertView 
          attribute:NSLayoutAttributeCenterY 
          relatedBy:NSLayoutRelationEqual 
          toItem:self.view 
          attribute:NSLayoutAttributeCenterY 
          multiplier:1.0f 
          constant:0.f]; 
Смежные вопросы