iOS 11 - 使用大标题模式时的UINavigationItem titleView

时间:2017-09-26 23:46:48

标签: ios navigationbar ios11 uinavigationitem titleview

我试图了解它是一个错误还是预期的行为。

iOS 10 及更早版本中,我们可以使用navigationItem.titleView设置自定义标题。
iOS 11 上,在设置我们的navigationItem.largeTitleDisplayMode = .always并设置navigationItem.titleView = <Some cool UIButton>时,它会显示两者正常的导航标题栏和大型导航标题。

插图: enter image description here

总结一下:

我们如何在大型导航标题上使用自定义titleView?

编辑:这是预期的结果:

enter image description here

2 个答案:

答案 0 :(得分:3)

我找不到任何关于此的文档,所以我玩了一下。在iOS 11中,您似乎无法将该标题设为按钮并在左侧显示较大的内容。

我不知道这是一个错误还是预期结果,因为它似乎是一个新功能。最新的(iOS 11)Human Interface Guidelines(HIG)讨论较大的标题标签是一种为用户提供清晰上下文的方法。 HIG还讨论了按钮之间的空间。但是,没有讨论使用按钮作为标题。

要重新创建,我设置了一个单视图项目。我将视图控制器嵌入到导航控制器中。

ViewController.swift的{​​{1}}中,我添加了以下代码:

viewDidLoad

这最终看起来像你的例子。

如果我

  • let titleButton = UIButton(type: .roundedRect) titleButton.setTitle("Hello Button!", for: UIControlState.normal) let navController = parent as! UINavigationController navController.navigationBar.topItem!.title = "Hello???" navController.navigationBar.topItem!.titleView = titleButton navController.navigationBar.prefersLargeTitles = true 设置为空字符串,或者注释掉该行:导航栏被拉伸,并且没有显示标题文本(或在Interface Builder中显示标题文本)

  • 注释.title,或将其设置为.prefersLargeTitles:导航栏是正常高度,按钮显示,但不显示标题文字。

  • 注明false行,AND:

    • titleView设置为.prefersLargeTitlestrue文字显示在左侧较大,导航栏的高度已拉伸。
    • title设置为.prefersLargeTitlesfalse文字显示在顶部中心,导航栏为正常高度。

更新:指向sample project on GitHub

的链接

答案 1 :(得分:1)

通过使用UINavigationBar的子类并手动更改视图层次结构,我能够用自定义视图替换导航栏大标题:

@interface MYNavigationBar : UINavigationBar

@end
@implementation MYNavigationBar

// ...

- (void)layoutIfNeeded
{
    [self setupTitle];
    [super layoutIfNeeded];
}

- (void)setupTitle
{
    // UINavigationBar
    // -> ...
    // -> _UINavigationBarLargeTitleView
    //   -> UILabel << Big Title Label
    //   -> UIView
    //     -> UILabel << Big Title Label animating from back button during transitions

    for (UIView *view in self.subviews) {
        NSString *className = NSStringFromClass(view.classForCoder);
        if ([className containsString:@"LargeTitleView"]) {
            for (UIView *view2 in view.subviews) {
                if ([view2 isKindOfClass:[UILabel class]]) {
                    [self convertLabel:(UILabel *)view2];
                }
                for (UIView *view3 in view2.subviews) {
                    if ([view3 isKindOfClass:[UILabel class]]) {
                        [self convertLabel:(UILabel *)view3];
                    }
                }
            }
        }
    }
}

- (void)convertLabel:(UILabel*)label
{
    // I kept the original label in the hierarchy (with the background color as text color)
    // and added my custom view as a subview. 
    // This allow the transformations applied to the original label to be also applied to mine.
}

请注意,由于这种技巧,苹果可能拒绝了您的应用。