我用了这个代码
self.navigationController?.navigationBar.titleTextAttributes =
[NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 20),
NSForegroundColorAttributeName: UIColor.whiteColor()]
我得到的错误是“找不到接受所提供参数的”init“的重载”
uifont(name:size:)
现在是一个可失败的初始值设定项--如果它找不到字体,它将返回nil
;如果您解压缩返回值,则应用程序崩溃。使用此代码可以安全地获取字体并使用它:
if let font = UIFont(name: "HelveticaNeue-Light", size: 20) {
self.navigationController?.navigationBar.titleTextAttributes =
[NSFontAttributeName: font,
NSForegroundColorAttributeName: UIColor.whiteColor()]
}
使用这个
self.navigationController?.navigationBar.titleTextAttributes =
[NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 20)!,
NSForegroundColorAttributeName: UIColor.whiteColor()!]
或者这个
if let font = UIFont(name:"HelveticaNeue-Light", size: 20.0) {
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: font]
}
另一种方法是在设置TitletExtAttributes
之前建立字典。这就避免了其他的事情,在您想要使用可失败的初始化器设置更多参数的情况下,这会更有好处。例如:
var attributes : [NSObject : AnyObject] = [NSForegroundColorAttributeName : UIColor.whiteColor()]
if let font = UIFont(name: "Helvetica", size: 20) {
attributes[NSFontAttributeName] = font
}
if let someData = NSData(contentsOfFile: "dataPath") {
attributes["imageData"] = someData
}
self.myObject.attributes = attributes