通过编程将自动布局约束添加到导航控制器 [英] Adding autolayout constraints to navigation controller programmatically

查看:58
本文介绍了通过编程将自动布局约束添加到导航控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向在导航栏上添加的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

来源:Apple文档

您需要将UINavigationBar子类化,然后使用initWithNavigationBarClass:toolbarClass:实例化UINavigationController来做进一步的事情.

You would need to subclass the UINavigationBar and then instantiate the UINavigationController using initWithNavigationBarClass:toolbarClass: to do something further.

尽管您正在寻找自定义导航栏的方法,但

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆