Ios 找不到“;初始”;它接受提供的参数

Ios 找不到“;初始”;它接受提供的参数,ios,xcode,swift,Ios,Xcode,Swift,我用了这个密码 self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 20), NSForegroundColorAttributeName: UIColor.whiteColor()] 我得到一个错误“找不到接受提供的参数的“init”的重载”使用这个 s

我用了这个密码

    self.navigationController?.navigationBar.titleTextAttributes =
        [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 20),
        NSForegroundColorAttributeName: UIColor.whiteColor()]
我得到一个错误“找不到接受提供的参数的“init”的重载”

使用这个

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]
}
UIFont(名称:size:)
现在是一个可失败的初始值设定项——如果找不到该字体,它将返回
nil
,如果你打开返回值,它将使你的应用程序崩溃。使用此代码可以安全地获取字体并使用它:

if let font = UIFont(name: "HelveticaNeue-Light", size: 20) {
    self.navigationController?.navigationBar.titleTextAttributes = 
            [NSFontAttributeName: font, 
             NSForegroundColorAttributeName: UIColor.whiteColor()]
}

另一种方法是在设置
titleTextAttributes
之前建立字典。这只会避免使用else,如果您还想使用可故障初始化器设置更多参数,则else将更为有用。例如:

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

问题略有不同,但本质上是相同的:您不需要
after
UIcolor.whiteColor()
,因为它不返回可选的。事实上,使用它会给你一个编译器错误。