在最新的Xcode版本中,不能在Swift中设置导航栏字体
以下代码在更新到Xcode 6.1之前运行正常,以适应iOS 8.1:
override func viewDidAppear(animated: Bool) { self.navigationController?.navigationBar.topItem?.title = "Home" self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34), NSForegroundColorAttributeName: UIColor.whiteColor()] }
问题是在NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34)
和我在这里得到的错误是:
! "Could not find an overload for 'init' that accepts the supplied arguments"
我发现这个原始代码在一个不同的StackOverflow问题,它是按预期工作,直到此更新(昨天下载)。 我的字体确实安装正确。
我现在应该以不同的方式编写这个代码,还是有一种全新的方式来设置我的导航栏字体?
谢谢!
哎呦。 我自己想到了这一点:
我在NSFontAttributeName声明后需要一个感叹号,因为它需要一个“NSString!”types。 也许它只需要一个“NSString”之前,但我现在没有问题。
工作路线:
NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 24)!
工作完整的代码:
override func viewDidAppear(animated: Bool) { self.navigationController?.navigationBar.topItem?.title = "Home" self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34)!, NSForegroundColorAttributeName: UIColor.whiteColor()] }
似乎现在似乎是一个愚蠢的问题。 希望这可以帮助别人!
您正在使用UIFont(name:
因为它被定义为
init?(name fontName: String, size fontSize: CGFloat) -> UIFont
failable intializer从链接中读取更多,所以它返回optional.You需要打开它,因为它需要AnyObject
不可选。
self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34)!, NSForegroundColorAttributeName: UIColor.whiteColor()]
谢谢Benji!
我改了一下,并将其应用到导航控制器的外观属性。
var navigationBarAppearance = UINavigationBar.appearance() navigationBarAppearance.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "OpenSans", size: 16)!, NSForegroundColorAttributeName: UIColor.whiteColor()]
最好把你的字体声明为有条件的,就像这样:
if let font = UIFont (name: "AdobeArabic-BoldItalic", size: 20) { UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font] }
这样做,确保你的字体已经find了,我已经安装了新的字体,并且在没有条件的情况下使用它,如果它发出了一个exception的解开一个可选的。
override func viewWillLayoutSubviews() { self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName : UIFont(name: "Roboto-Regular", size: 14)!] }