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
来源:Apple Docs
您需要将 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.
这篇关于以编程方式向导航控制器添加自动布局约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以编程方式向导航控制器添加自动布局约束
基础教程推荐
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
