我在文档中找不到关于这个的任何资料,所以我尝试了一下。似乎在iOS 11中,你将无法将标题作为按钮显示在左边并且让它变大。
我不知道这是一个bug还是预期结果,因为它似乎是一个新功能。最新的(iOS 11)人机界面指南(HIG)讨论了更大的标题标签作为提供给用户清晰上下文的一种方式。 HIG还讨论了按钮之间的间隔。但是,没有讨论使用按钮作为标题。
要重新创建,请设置一个单视图项目,并在其中嵌入视图控制器到导航控制器中。
在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
这最终看起来会像你的示例一样。
如果我:
将.title
设置为空字符串或注释掉该行:导航栏被拉伸,没有标题文本显示(或在Interface Builder中设置的标题文本显示)
注释掉.prefersLargeTitles
,或将其设置为false
:导航栏是正常高度,按钮显示,但没有标题文本显示。
注释掉titleView
行,然后:
.prefersLargeTitles
设置为true
:左侧显示大号title
文本,并且导航栏的高度被拉伸。.prefersLargeTitles
设置为false
:顶部中心显示title
文本,并且导航栏高度正常。更新:链接到GitHub上的示例项目
通过使用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.
}