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这个一定要注意。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容