Xcode 6.1 titleTextAttributes

Ben*_*Ben 11 swift xcode6

所以我正在编写这个应用程序,它具有彩色导航栏和该栏中标题的字体,UIBarButtonItems的字体应为白色和特定字体.我在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)
Run Code Online (Sandbox Code Playgroud)

但是使用Xcode 6.1我在每一行中都会出错,我真的不知道,有什么意思..

在此输入图像描述

文本属性是[NSObject:AnyObject]?.这正是我写下来的.有人有解决方案吗?

mus*_*afa 37

我认为问题是因为他们已经改变UIFont了6.1中的初始化程序,所以它可以返回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()]
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您确定字体对象不可能nil,则可以使用隐式解包的可选语法.在这种情况下,您将承担运行时崩溃的风险.这是怎么做的.

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