Swift3.0 设置NSAttributedString时Attributes错误处理

在设置NSAttributedString时,Attributes是一个字典,如下设置:

[NSFontAttributeName:UIFont(name:"PingFangSC-Regular", size:10.0),NSForegroundColorAttributeName:UIColor.white]

在设置时没有错误,在运行时错误如下:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue pointSize]: unrecognized selector sent to instance 0x618000051790'

注意,从错误上是看不出来是什么问题的哟,为此被坑了一下午,最后终于发现使用UIFont.systemFont(ofSize:14)确不不报错,原来UIFont.systemFont(ofSize:14)返回是一个UIFont,而:UIFont(name:"PingFangSC-Regular", size:10.0)返回是一个UIFont?实例,问题确定了,解决就方便了,只需要使用

[NSFontAttributeName:UIFont(name:"PingFangSC-Regular", size:10.0)!,NSForegroundColorAttributeName:UIColor.white]

系统正常,所以在Swift中optional这个一定要注意。

你可能感兴趣的:(Swift3.0 设置NSAttributedString时Attributes错误处理)