iOS 12 中的自定义导航标题

Custom Navigation Title in 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!)

但问题是我必须在离开视图时删除子视图,否则我添加的任何内容也会出现在 table 视图中。

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    if navigationBar != nil {
        titleView?.removeFromSuperview()
    }
}

这有点让我觉得我没有做正确的事,而且我发现在离开对话时很难向这些子视图添加淡出动画。 (即 iOS 上的本地消息应用程序)。

那么在 iOS12 中创建自定义标题导航栏的正确方法是什么?

场景

创建您的自定义 titleView 并将其分配给 navigationItem.titleView 是您想要的。在旧系统上(iOS 11 之前),您可能只需要在 titleView.

上调用 sizeToFit()

这样你就可以创建这个titleView

Swift

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
}

Obj-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

这些行对标题视图的大小没有影响:

let rect = CGRect(x: 0, y:0, width: 150, height: 88)
titleView = UIView(frame: rect)

而是(或另外)给您的标题视图一个宽度限制和一个高度限制。这就是运行时如何知道您想要的大小。