gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 05:08:34 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com