我的视图有一个条件,根据用户是创建新对象还是查看现有对象,它可能会或可能不会在底部显示工具栏。我试图使用autolayout根据该工具栏的外观/消失一致地向上或向下移动按钮。
我遇到了这个问题,看起来很简单。
[self.doneButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.bottomLayoutGuide attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.doneButton attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20.0]];
我尝试了这个替代方案,剪切并粘贴了Apple文档UIViewController类参考
UIButton *button = self.doneButton;
[button setTranslatesAutoresizingMaskIntoConstraints: NO];
id bottomGuide = self.bottomLayoutGuide;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (button, bottomGuide);
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat: @"V:[button]-20-[bottomGuide]"
options: 0
metrics: nil
views: viewsDictionary]
];
[self.view layoutSubviews]; // You must call this method here or the system raises an exception
无论哪种方式,同样的问题。当没有工具栏时,按钮显示正确,从底部20px。当有工具栏显示时,它会更高,超过100px。
所以我添加了一个NSLog来查看bottomLayoutGuide属性。
CGFloat bar = self.bottomLayoutGuide.length;
NSLog(@"bottom bar is %f",bar);
这是布局后的
NSLog(@"button height is %f",self.view.bounds.size.height - self.doneButton.frame.origin.y);
从控制台产生这个
[Line 114] bottom bar is 93.000000
[Line 126] button height is 143.000000
93来自哪里?如果我只是从底部放置20的标准约束,则按钮隐藏在工具栏后面。如果bottomLayoutGuide
返回预期结果,那将是桃子。
我尝试过的其他一些事情包括将这些方法移动到其他各种事件,例如viewWillAppear
,viewDidAppear
,viewDidLoad
和viewDidLayoutSubviews
。没有得到改善。我想我可以硬编码工具栏的高度,但考虑到autolayout
和布局指南的意图,这没有任何意义。