Swift Xcode 6.1 titleTextAttributes

Swift Xcode 6.1 titleTextAttributes,swift,xcode6,Swift,Xcode6,所以我正在写这个应用程序,它有彩色的导航栏,标题的字体应该是白色的,并且是特定的字体。我在AppDelegate中使用了这两行代码来实现这一点 UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "SourceSansPro-Regular", size: 22), NSForegroundColorAttributeName : UIColor.whiteColor

所以我正在写这个应用程序,它有彩色的导航栏,标题的字体应该是白色的,并且是特定的字体。我在AppDelegate中使用了这两行代码来实现这一点

    UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "SourceSansPro-Regular", size: 22), NSForegroundColorAttributeName : UIColor.whiteColor()]
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName : UIFont(name: "SourceSansPro-Regular", size: 22), NSForegroundColorAttributeName : UIColor.whiteColor()], forState: .Normal)
但是在Xcode 6.1中,我在每一行中都会遇到一个错误,我真的不知道这意味着什么


文本属性是[NSObject:AnyObject]?。那正是我写下的。。有人对此有解决方案吗?

我认为问题是因为他们在6.1中更改了
UIFont
的初始值设定项,因此它可以返回
nil
。这是正确的行为,因为如果输入错误的字体名称,则无法实例化
UIFont
。在这种情况下,您的字典将变成
[NSObject:AnyObject?]
,这与
[NSObject:AnyObject]
不同。您可以先初始化字体,然后使用
if let
语法。下面是如何做到这一点

let font = UIFont(name: "SourceSansPro-Regular", size: 22)
if let font = font {
    UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : font, NSForegroundColorAttributeName : UIColor.whiteColor()]
}
或者,如果您确定字体对象不是
nil
,则可以使用隐式展开的可选语法。在这种情况下,您将承担运行时崩溃的风险。下面是如何做到这一点

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "SourceSansPro-Regular", size: 22)!, NSForegroundColorAttributeName : UIColor.whiteColor()]

是的,就是这样!非常感谢你。我认为初始值设定项可以返回nil是非常令人困惑的,但这是有意义的:)