0

我正在創建一個需要添加爲UIWindow的子視圖的customalertview。我已經正確設置了它的子視圖的約束條件,但是我很困惑關於何時/如何設置視圖本身相對於窗口的約束。將子視圖添加到UIWindow時Autolayout

我希望alertview的寬度爲屏幕寬度的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];