以编程方式向导航控制器添加自动布局约束 [英] Adding autolayout constraints to navigation controller programmatically
问题描述
我正在尝试将约束添加到我在导航栏上添加的 UI 标签.UI 标签显示一个正在运行的计时器
I am trying to add constraints to a UI label I added on a navigation bar. The UI label shows a running timer
这是我的代码,
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]];
但我在运行应用程序时收到错误消息无法修改控制器管理的 UINavigationBar 的约束".
But I get the error 'Cannot modify constraints for UINavigationBar managed by a controller' when I run the app.
如何添加此约束?
推荐答案
简而言之:你不能.
导航控制器管理导航栏和可选导航工具栏的创建、配置和显示.允许自定义导航栏与外观相关的属性,但绝不能直接更改其框架、边界或 alpha 值……导航控制器使用导航项对象(UINavigationItem 的实例)动态构建导航栏的内容类)与导航堆栈上的视图控制器相关联
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
您需要将 UINavigationBar
子类化,然后使用 initWithNavigationBarClass:toolbarClass:
实例化 UINavigationController
以做进一步的事情.
You would need to subclass the UINavigationBar
and then instantiate the UINavigationController
using initWithNavigationBarClass:toolbarClass:
to do something further.
如果您正在寻找自定义导航栏的方法,UIKit 用户界面指南 是了解您可以做什么的良好开端.但是,如果它将是一个文本标签,请考虑设置栏的 title
属性,例如.
Though if you're looking for ways to customize the navbar, UIKit User Interface Guide is a good start to know what you may be able to do. But if it's going to be a text label, consider setting the bar's title
property, for example.
这篇关于以编程方式向导航控制器添加自动布局约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!