'UIFont'不能转换为'UIFont?'

Vis*_*ran 39 swift xcode7

所以我今天晚上将我的XCode更新为7.3.

在我的一个项目中,我设置字体的几个标签出现以下错误:

'(name: String, size: CGFloat) -> UIFont' is not convertible to '(name: String, size: CGFloat) -> UIFont?'
Run Code Online (Sandbox Code Playgroud)

编辑:这是导航栏中标题视图的代码:

let aTitleFrame: CGRect = CGRectMake(0, aHeaderTitleSubtitleView.frame.midY / 2, 200, 24)
let aTitleView: UILabel = UILabel(frame: aTitleFrame)
aTitleView.backgroundColor = UIColor.clearColor()
aTitleView.font = UIFont(name: "Roboto-Regular", size: 15) // ERROR POPS UP HERE
aTitleView.textAlignment = NSTextAlignment.Center
aTitleView.textColor = UIColor.whiteColor()
Run Code Online (Sandbox Code Playgroud)

这是我的UILabel的归因字符串代码:

let aAttributedFundLabel: NSMutableAttributedString = NSMutableAttributedString(string: "Raising\n$ \(fund)")
aAttributedFundLabel.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSRange(location: 0, length: 7))
aAttributedFundLabel.addAttribute(NSFontAttributeName, value: UIFont(name: "Roboto-Regular", size: 15)!, range: NSRange(location: 0, length: 7)) // ERROR POPS UP HERE 
aAttributedFundLabel.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: NSRange(location: 8, length: fund.characters.count + 2))
aAttributedFundLabel.addAttribute(NSFontAttributeName, value: UIFont(name: "Roboto-Regular", size: 16)!, range: NSRange(location: 8, length: fund.characters.count + 2)) // ERROR POPS UP HERE
startupFund.attributedText = aAttributedFundLabel
Run Code Online (Sandbox Code Playgroud)

这只发生在我整个项目中的两个文件中.

我打开了另一个项目,但我能够构建并运行它没有任何错误,即使我也为那里的多个标签设置了字体.

知道为什么会这样吗?

TIA!

mat*_*att 115

在其他地方,有人建议你有这个:

aTitleView.font = UIFont(name: "Roboto-Regular", size: 15)
Run Code Online (Sandbox Code Playgroud)

...你应该尝试写这个:

aTitleView.font = UIFont.init(name: "Roboto-Regular", size: 15)
Run Code Online (Sandbox Code Playgroud)

我不能相信这一点(因为我无法重现这个错误)所以我只是在猜测!但要知道它是否真的有用会非常有趣.

  • 有点麻烦!非常感谢!:) (3认同)
  • 有同样的问题,我在懒惰的var实例化中设置它; 在没有init的情况下在外面工作. (3认同)

Pie*_*Rea 9

我也有这个问题.为我修复的是关闭整个模块优化.

Bulid设置> Swift编译器 - 代码生成>优化级别

我把它设置为Fastest(整个模块优化).当我将其设置为None时,我不再有这个问题了.对于上下文,这是一个包含Objective-C和Swift的混合代码库.

  • 同上.跟我一样.我只能在归档项目时产生此错误.在调试模式下构建+运行没有错误.所以,当然,我查看了我的调试/发布优化并测试了Fast(WMO)与Fast [-O].这样做了,但我想保留WMO的性能原因,所以我将暂时使用`UIFont.init(名字:`). (4认同)