许多产品为了保持UI简介,并不希望导航栏上有太多文字。所以通常都是不要返回的标题,保留一个"<"图标即可。
常规的方法是替换self.navigationItem.leftBarButtonItems
,要写不少代码
UIButton *leftButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
[leftButton addTarget:self action:@selector(leftBarButtonClick) forControlEvents:UIControlEventTouchUpInside];
[leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
spaceItem.width = -10.0f;
if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 11.0)) {
leftButton.contentEdgeInsets =UIEdgeInsetsMake(0, -15, 0, 0);
leftButton.imageEdgeInsets =UIEdgeInsetsMake(0, -15, 0, 0);
}
self.navigationItem.leftBarButtonItems = @[spaceItem,leftItem];
另一种方法是修改上一级的self.navigationItem
,iOS导航栏,返回的文字显示策略是
- 判断上一级的
navigationItem.title
- 如果不为nil,显示它
- 如果是nil,显示 "返回"
self.navigationItem.title
从哪里来?当一个UIViewController
要显示的时候,会检查navigationItem.title
有没有。
如果没有,就将self.tilte
给到self.navigationItem.title
。接着检查self.navigationItem.titleView
,如果没有,则创建一个UILabel并设置title。
明白了这一点,最简单的修改就是自己创建self.navigationItem.title
和self.navigationItem.titleView
。用面向切面的方法,可以一次性解决所有页面。
[UIViewController aspect_hookSelector:@selector(setTitle:)
withOptions:AspectPositionAfter
usingBlock:^(id<AspectInfo> aspectInfo, NSString *title) {
UIViewController *vc = aspectInfo.instance;
vc.navigationItem.titleView = ({
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
titleLabel.text = title;
titleLabel;
});
vc.navigationItem.title = @"";
} error:NULL];