ios - 以编程方式向导航 Controller 添加自动布局约束

标签 ios autolayout ios-autolayout

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

这是我的代码,

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]];

但是当我运行应用程序时,我收到错误“无法修改由 Controller 管理的 UINavigationBar 的约束”。

如何添加此约束?

最佳答案

简而言之:你不能。

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 属性,例如。

关于ios - 以编程方式向导航 Controller 添加自动布局约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28708074/

相关文章:

ios - UIView subview 自动布局问题

ios - 如何在 Storyboard Xcode 8 中启用自动布局

ios - 为 uitableview 创建边框

objective-c - 将 NSString 转换为 Integer 并检查它是否小于或等于某个值

iOS 简单视觉格式布局不起作用

ios - iphone XR、XS Max 上的 modalPresentationStyle formSheet 问题

ios - 控制台中的约束警告

ios - 为什么 UIImageView 不会更改为已设置一次的不同图像?

ios - 如何在 UITextField 中显示整数值?

ios - 不等式约束 iOS 的宽度