ios - iOS 12 中的自定义导航标题
问题描述
我正在尝试在 iOS 应用程序上实现自定义导航标题。
故事板看起来像这样:
我想要自定义导航标题的地方是最后一个视图(消息视图),因为我使用图像和文本,这意味着我需要自定义宽度和高度。如果我这样做需要这个viewDidLoad
:
let rect = CGRect(x: 0, y:0, width: 150, height: 88)
titleView = UIView(frame: rect)
......
titleView?.addSubview(imageView)
......
titleView?.addSubview(label)
navigationItem.titleView = titleView
标题的高度被封锁到 44pt。
但我设法做到的是将子视图添加到导航栏:
var navigationBar: MessagesNavigationBar? {
guard let navigationBar = navigationController?.navigationBar as? MessagesNavigationBar else {
return nil
}
return navigationBar
}
而在viewDidLoad
let rect = CGRect(x: 0, y:0, width: 150, height: 88)
titleView = UIView(frame: rect)
......
titleView?.addSubview(imageView)
......
titleView?.addSubview(label)
navigationBar?.addSubview(titleView!)
但问题是当我离开视图时我必须删除子视图,否则我添加的任何内容也会出现在表格视图中。
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if navigationBar != nil {
titleView?.removeFromSuperview()
}
}
这有点让我觉得我没有做正确的事情,当我离开对话时,我发现很难为这些子视图添加淡出动画。(即 iOS 上的本机消息应用程序)。
那么在 iOS 12 中创建自定义标题导航栏的正确方法是什么?
场景
解决方案
创建您的自定义titleView
并将其分配给navigationItem.titleView
您想要的。sizeToFit()
在较旧的系统(iOS 11 之前)上,您可能只需要调用titleView
.
这样你就可以创建这个titleView
迅速
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView()
NSLayoutConstraint.activate([
imageView.heightAnchor.constraint(equalToConstant: 20),
imageView.widthAnchor.constraint(equalToConstant: 20)
])
imageView.backgroundColor = .red
let titleLabel = UILabel()
titleLabel.text = "Custom title"
let hStack = UIStackView(arrangedSubviews: [imageView, titleLabel])
hStack.spacing = 5
hStack.alignment = .center
navigationItem.titleView = hStack
}
对象-C
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc] init];
[NSLayoutConstraint activateConstraints:@[
[imageView.heightAnchor constraintEqualToConstant:20],
[imageView.widthAnchor constraintEqualToConstant:20]
]];
imageView.backgroundColor = [UIColor redColor];
UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.text = @"Custom title";
UIStackView *hStack = [[UIStackView alloc] initWithArrangedSubviews:@[imageView, titleLabel]];
hStack.spacing = 5;
hStack.alignment = UIStackViewAlignmentCenter;
self.navigationItem.titleView = hStack;
}
您可能还需要有一组正确的自动布局约束或使用UIStackView
.
推荐阅读
- vue.js - Vuetify - 如何轻松访问 v-select 项目文本值?
- python - 发生崩溃时自动重新运行脚本
- heroku - Heroku Hobby Dyno 混乱
- asp.net-core - SignalR Core 和 ASP.NET Core 2.x:协商时每 5 秒获得 404
- snmp - 将 SNMP ASN.1 映射到 C++ 数据类型
- angular - 订阅一个嵌套的 observable
- node.js - 语义发布是否支持与 Jenkins CI 的集成?
- java - 启动层初始化期间发生错误 - Eclipse Java
- php - PHP & MYSQL:mysqldump 跳过表
- xamarin - 在 2018 年 9 月 18 日发布之后,是否有人能够在模拟器上运行 ios ui 测试?