以编程方式向导航控制器添加自动布局约束

Adding autolayout constraints to navigation controller programmatically

我正在尝试向我在导航栏上添加的 UI 标签添加约束。 UI 标签显示 运行ning 定时器

这是我的代码,

self.label = [[UILabel alloc] initWithFrame:CGRectMake(550, 15, 150, 14)];
self.label.text = @"Label";
[self.label setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.navigationController.navigationBar addSubview:self.label];

[self.navigationController.navigationBar addConstraint:[NSLayoutConstraint constraintWithItem:self.label
                                                       attribute:NSLayoutAttributeTrailing
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:self.navigationController.navigationBar
                                                       attribute:NSLayoutAttributeTrailing
                                                      multiplier:1.0f
                                                        constant:-20.0f]];

但是当我 运行 应用程序时,我收到错误 'Cannot modify constraints for UINavigationBar managed by a controller'。

如何添加此约束?

简而言之:你不能。

The navigation controller manages the creation, configuration, and display of the navigation bar and optional navigation toolbar. It is permissible to customize the navigation bar’s appearance-related properties but you must never change its frame, bounds, or alpha values directly ... A navigation controller builds the contents of the navigation bar dynamically using the navigation item objects (instances of the UINavigationItem class) associated with the view controllers on the navigation stack

Source: Apple Docs

您需要对 UINavigationBar 进行子类化,然后使用 initWithNavigationBarClass:toolbarClass: 实例化 UINavigationController 以进一步执行某些操作。

尽管如果您正在寻找自定义导航栏的方法,UIKit User Interface Guide 是了解您可以做什么的良好开端。但是,如果它将成为文本标签,请考虑设置栏的 title 属性,例如。

我最终将计时器标签添加为导航栏上的右按钮栏项目。这是一种骇人听闻的方式。但由于无法添加约束,因此这是一种解决方法。

另一种方式,在将您的自定义视图作为子视图添加到 UINavigationBar 后,通过更新 .frame 属性 以老式方式手动设置位置和大小。这不是 "flexible" 解决方案,但简单快捷。