我在故事板中有详细视图。我想在满足特定条件时在该视图中加载另一个Nib。但是,当我这样做时,自动布局一切都搞砸了你。
我试图在UIWebView上方显示UIView,就像叠加视图一样。我希望UIView在顶部和底部布局指南之间具有相同的设备比例,最大高度为400.
以下是我用来加载Nib的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
// Do any additional setup after loading the view, typically from a nib.
UINib *s = [UINib nibWithNibName:@"Square1" bundle:nil];
NSArray *array = [s instantiateWithOwner:self options:nil];
StopView *stopView = (StopView *)[array objectAtIndex:0];
[stopView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:stopView];
id topGuide = self.topLayoutGuide;
id bottomGuide = self.bottomLayoutGuide;
UIWebView *webView = self.detailWebView;
NSDictionary *views = NSDictionaryOfVariableBindings(stopView, topGuide, bottomGuide, webView);
// this is here to stop the auto layout from reporting that the guides has
// ambiguous layout
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[topGuide]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[bottomGuide]|" options:0 metrics:nil views:views]];
// center the stop view in the super view, both lines below are needed
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-(>=12)-[stopView(<=400)]-(>=12)-|"
options: 0
metrics:nil
views:views]];
// set the height to a ratio of the width
NSLayoutConstraint *con2 = [NSLayoutConstraint constraintWithItem:stopView
attribute:NSLayoutAttributeWidth
relatedBy:0 toItem:stopView
attribute:NSLayoutAttributeHeight
multiplier:0.66667f constant:0];
[self.view addConstraint:con2];
// center the Stop View X,Y with the super view
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:stopView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0f constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:stopView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.0f constant:0]];
NSLog(@"Calling configureView from viewDidLoad");
[self configureView];
}
以下是一些屏幕截图:
正如您在第三个屏幕截图中看到的那样,我的背景没有显示。您可以在设计模式中看到位于顶部的UILabel的 T 。
我做错了什么?
答案 0 :(得分:1)
对于垂直约束,您需要在字符串前放置一个“V:”。要使视图最大为400,但是对于较小的屏幕,要给出顶部和底部间距约束的最大值,则需要使用约束的优先级,
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=12)-[stopView(==400@900)]-(>=12)-|"
options: 0
metrics:nil
views:views]];
系统将尝试使stopView的高度尽可能接近400,同时保持与顶部和底部至少12的间距。