iOS11 UIToolBar自动扩展

iOS 11 UIToolBar automatic expansion

我正在以编程方式创建一个 UIToolBar,它工作正常,除了 iPhone X,我希望工具栏根据 phone 的方向展开。如果工具栏是使用界面生成器创建的,则扩展有效。

我没有设置任何高度限制,即使是通过自动布局掩码隐式设置也是如此。

代码:

UIToolbar* toolbar = [[UIToolbar alloc] init];
toolbar.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:toolbar];
[self.view addConstraints:@[
                            [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:toolbar attribute:NSLayoutAttributeLeft multiplier:1 constant:0],
                            [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:toolbar attribute:NSLayoutAttributeBottom multiplier:1 constant:0],
                            [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:toolbar attribute:NSLayoutAttributeRight multiplier:1 constant:0]]];

那么,我应该怎么做才能使工具栏正常运行?

好的,部分答案是使用安全区域self.view.safeAreaLayoutGuide,或者使用上下文:

[NSLayoutConstraint constraintWithItem:self.view.safeAreaLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:toolbar attribute:NSLayoutAttributeBottom multiplier:1 constant:0],

'partial'部分是指IB toolbar高度为49,manual toolbar高度为44。

这对我来说已经足够了,但如果有人能够 fix/explain 44-49 的差异,我会将其标记为解决方案。

编辑:我找到了缺失的部分。

我没有打电话给 invalidateIntrinsicContentSize。添加来自 willTransitionToTraitCollection: withTransitionCoordinator: 的呼叫修复了该问题。不知何故,在去年左右,我错过了工具栏在紧凑模式下改变其大小的情况。