2017-06-18 34 views
8

我有一个要求,我必须使用带有红色大标题的UINavigationBar当“prefersLargeTitles”设置为true时,更改导航栏标题的文本颜色

目前,我有以下代码:

func prepareNavigationController() { 
    let navController = UINavigationController(rootViewController: self) 
    navController.navigationBar.prefersLargeTitles = true 
    navigationItem.searchController = UISearchController(searchResultsController: nil) 
    navigationItem.hidesSearchBarWhenScrolling = false 
    navController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.red] 
} 

但它实际上没有着色的标题标签为红色。这是结果:

Ignored title color

但改变prefersLargeTitles假做正确的事,和我的标题是红色的。

navController.navigationBar.prefersLargeTitles = false

Tinted Title

我不能完全肯定,如果这是一个错误,因为在写这篇文章的时候,我们仍然在第一个测试版本,或者如果这是故意的行为,主要是因为我的天堂苹果的任何应用程序都不会为之前的大型游戏着色。有什么办法可以让大标题有我想要的任何颜色?

+0

我在寻找同样的事情!我还没有发现如何改变它,也许因为它是苹果公司尚未实施的第一个测试版。 – Philippe

+0

也许这可能是正确的答案https://stackoverflow.com/a/46007201/7048642 –

回答

13

有一个新的UINavigationBar的财产 “largeTitleTextAttribute” 应该在这方面帮助。

largeTitleTextAttribute

这里是一个示例代码,您可以添加到您的视图控制器viewDidLoad方法

 navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.blue] 

enter image description here

这里是一个示例代码和截图没有largeTitleTextAttributes集,但barStyle设置为黑色。

 navigationController?.navigationBar.barStyle = .black 

enter image description here

这里是没有largeTitleTextAttributes集的截图,但barStyle设置为.DEFAULT

 navigationController?.navigationBar.barStyle = .default 

enter image description here

+0

有趣。这是新的Beta 3吗?我还没有下载,但我现在要做,并检查出来。 –

+0

对测试版3来说是新的。或者至少我现在才注意到它。 – assb10yr

+0

我会在几个小时内确认(因特网速度很慢),因为Beta 2上不存在这个符号。 –

2

不知道这是否是beta 1 & 2中的错误,但是这里有一种设置颜色的方法。这是一个“哈克”解决方法,但它应该工作,直到Apple修复此问题。在Objective-C和Swift版本中,该代码都在viewDidAppear:方法中。

的Objective-C:

dispatch_async(dispatch_get_main_queue(), ^{ 
    for (UIView *view in self.navigationController.navigationBar.subviews) { 
     NSArray <__kindof UIView *> *subviews = view.subviews; 
     if (subviews.count > 0) { 
      UILabel *label = subviews[0]; 
      if (label.class == [UILabel class]) { 
       [label setTextColor:[UIColor redColor]]; 
      } 
     } 
    } 
}); 

斯威夫特:

DispatchQueue.main.async { 
    for view in self.navigationController?.navigationBar.subviews ?? [] { 
    let subviews = view.subviews 
    if subviews.count > 0, let label = subviews[0] as? UILabel { 
      label.textColor = UIColor.red 
} } } 
0

这里是工作的代码使用大标题和设置的文本颜色无论是在iOS11 +还是在旧版本的iOS版本中,小型和大型游戏都是白色的。

// Will apply to versions before iOS 11 
navigationController?.navigationBar.titleTextAttributes = [ 
    NSAttributedStringKey.foregroundColor: UIColor.white 
] 

if #available(iOS 11.0, *) { 
    navigationController?.navigationBar.prefersLargeTitles = true 
    navigationController?.navigationBar.largeTitleTextAttributes = [ 
     NSAttributedStringKey.foregroundColor: UIColor.white 
    ] 
} 

(曾经有在Xcode中的错误,但现在看来是固定的)