这是来自与 OP 同一团队的开发人员的回答。
经过一轮研究,我们发现问题出在我们这边:
- (NSArray *)toolbarItems
{
return [self toolbarItemsWithRunningAdditionalAnimation:NO];
}
原始开发者制定了该方法toolbarItemsWithRunningAdditionalAnimation
每次调用该方法时都返回新对象。当转到这个控制器时 iOS 会调用toolbarItems
至少 3 次,所以每次我们让 iOS 感到困惑时,都会给它新的对象,因此它会在无限循环中重新计算自动布局约束。我们最初的修复也有效,但是它变得过时了,因为我们开始总是返回相同的项目数组,例如:
- (NSArray *)toolbarItems {
if (_cachedToolbarItems) { return _cachedToolbarItems; }
_cachedToolbarItems = [self toolbarItemsWithRunningAdditionalAnimation:NO];
return _cachedToolbarItems'
}
我们在我们的应用程序中执行以下操作(伪代码):
UIToolbar *toolbar = self.navigationController.toolbar;
NSArray <UIBarButtonItem *> *items = @[
flexibleSpace,
share,
flexibleSpace,
play,
flexibleSpace,
stats,
flexibleSpace
];
[toolbar setItems:items animated:animated];
[self.navigationController setToolbarHidden:NO animated:animated];
导致自动布局约束无限计算的有问题的项目是share
and stats
。他们的共同点是——他们都是使用-[UIBarButtonItem initWithImage:style:target:action:]
初始化程序。当我们开始使用另一个初始化器时:
UIButton *customShareButton = ... // we create button ourselves.
UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithCustomView: customShareButton];
问题就消失了。