NSFontAttributedString worked before XCode 6.1

安稳与你 提交于 2019-11-27 02:16:22

Xcode 6.1 comes with Swift 1.1 that supports constructors that can fail. UIFont initialisation can fail and return nil. Also use string: when creating NSAttributedString:

if let font = UIFont(name: "Voyage", size: 20.0) {
    let timeFont = [NSFontAttributeName:font]
    var attrString3 = NSAttributedString(string: "(Time)", attributes : timeFont)
}

There are two reasons your code is failing to compile:

  • The initializer for NSAttributedString that you want to use now requires the explicit labeling of the string parameter
  • The UIFont initializer that you are using now returns an optional (i.e., UIFont?), which needs to be unwrapped before you pass it in the attributes dictionary.

Try this instead:

let font = UIFont(name: "Voyage", size: 20.0) ?? UIFont.systemFontOfSize(20.0)
let attrs = [NSFontAttributeName : font]
var attrString3 = NSAttributedString(string: "(Time)", attributes: attrs)

Note the use of the new coalescing operator ??. This unwraps the optional Voyage font, but falls back to the System Font if Voyage is unavailable (which seems to be the case in the Playground). This way, you get your attributed string regardless, even if your preferred font can't be loaded.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!