首页 > 解决方案 > 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 中创建自定义标题导航栏的正确方法是什么?

场景

在此处输入图像描述

标签: iosswiftxcodeuinavigationcontrolleruinavigationbar

解决方案


创建您的自定义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.


推荐阅读