Roi*_*lia 7 uinavigationitem titleview navigationbar ios ios11
我试图理解它是一个错误或它是预期的行为.
在iOS 10及更早版本中,我们可以使用设置自定义标题navigationItem.titleView.
在iOS的11,我们设置时navigationItem.largeTitleDisplayMode = .always并设置navigationItem.titleView = <Some cool UIButton>它的显示都正常航行标题栏和导航的大标题.
总结一下:
我们如何在大型导航标题上使用自定义titleView?
编辑:这是预期的结果:
我找不到关于此的任何文档,所以我玩了一点。似乎在iOS 11中,您将无法获得该标题作为按钮,并在左侧显示大字体。
我不知道这是错误还是预期的结果,因为它似乎是一项新功能。最新的(iOS 11)人机界面指南(HIG)讨论了较大的标题标签,这是一种为用户提供清晰上下文的方法。HIG还讨论了按钮之间的空间。但是,这里没有讨论使用按钮作为标题。
要重新创建,我设置了一个Single View项目。我将视图控制器嵌入导航控制器中。
在ViewController.swift的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
Run Code Online (Sandbox Code Playgroud)
最终看起来像您的示例。
如果我:
设置.title为空字符串,或将行标记为空:导航栏被拉伸,并且没有标题文本显示(或在Interface Builder中显示的标题文本显示)
标记为.prefersLargeTitles,或将其设置为false:导航栏为正常高度,显示按钮,但不显示标题文本。
指出这一titleView行,并且:
.prefersLargeTitles设置保留为true:title文本在左侧显示大,导航栏的高度被拉伸。.prefersLargeTitles为false:title文本显示在顶部中央,导航栏为正常高度。更新:链接到GitHub上的示例项目
我能够通过使用子类UINavigationBar并手动更改视图层次结构,用自定义视图替换导航栏大标题:
@interface MYNavigationBar : UINavigationBar
@end
Run Code Online (Sandbox Code Playgroud)
@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.
}
Run Code Online (Sandbox Code Playgroud)
请注意,Apple可能会因为这个技巧而拒绝您的应用程序。