自动收缩导航栏标题iOS 7或更高版本

时间:2015-04-08 01:38:37

标签: ios objective-c

我想知道什么是让UINavigationBar标题在太长的时候自动缩小到最小字体大小的最佳方法是什么?

以下是我的问题示例

正常

enter image description here

太长(需要缩小标签)

enter image description here

这是我用来为UINavigationBar做样式的代码

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithColor:[UIColor greenColor]]
                                   forBarMetrics:UIBarMetricsDefault];

[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName   : [UIColor whiteColor],
                                                       NSFontAttributeName              : [fontWithName:@"Helvetica-Bold" size:18.0]}];

[[UINavigationBar appearance] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin];

1 个答案:

答案 0 :(得分:3)

最常见的解决方案是使用标题的自定义视图。但是你不能使用UIAppearance来做这个,你需要在你推动的每个UIViewController上做这个,或者做一个UINavigationBar的类别,并在每次改变标题文本时添加这个逻辑(不确定这是否会但是,如果它是一个好主意,或者创建一个新的adhoc方法。

例如(把它放在你的UIViewController的viewDidLoad中):

UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 40)];
titleLabel.text = @"Your very long title";
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.adjustsFontSizeToFitWidth = YES; // As alternative you can also make it multi-line. 
titleLabel.minimumScaleFactor = 0.5;     
self.navigationItem.titleView = titleLabel;