Swift 3错误:[_SwiftValue pointSize]无法识别的选择器发送到实例

Leo*_*nid 28 string nsstring uifont ios swift

我刚刚将项目迁移到swift 3并因为一个问题看到了很多崩溃:

终止应用程序由于未捕获的异常"NSInvalidArgumentException",原因是:" - [_ SwiftValue的pointsize]:无法识别的选择发送到实例

出现这种错误的原因是:

[NSAttributedString(NSExtendedStringDrawing) boundingRectWithSize:options:context:]
Run Code Online (Sandbox Code Playgroud)

我注意到的是,如果我将String转换为NSString并调用boundingRectWithSize它,它将抛出该错误.它似乎也发生在许多其他部分,例如,如果我在故事板中发送了一个视图控制器标题,它会抛出相同的错误.

谁有同样的问题?

重现问题:

在Xcode 8中创建一个新的Swift 3项目,并在viewDidLoad中添加以下行:

let attributes: [String: AnyObject?] = [
            NSFontAttributeName: UIFont.systemFont(ofSize: 14)
        ]
    let boundingRect = ("hello" as NSString).boundingRect(with: CGSize(width: 100, height: 100), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
Run Code Online (Sandbox Code Playgroud)

但正如我所说,它在许多其他地方崩溃,因为UIKit似乎在很多部分内部使用这种方法

Phi*_*lls 26

如果我使用你的测试代码,但是让数据类型attributes默认,它不会崩溃.那是:

let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 14)]
Run Code Online (Sandbox Code Playgroud)

按住Option键点击变量即可[String : UIFont].

一点额外的测试,表明它与可选对象有关; [String: AnyObject]似乎工作正常.

编辑:毕竟,我决定阅读说使用的文档[String: Any].:)

  • 好的捕获,菲利普.这里有一点,如果有人使用自定义字体,则应该解开字体:`UIFont(名称:UIFont.lightFontName(),size:14)! (29认同)
  • 是的,因为`UIFont(name:size :))返回一个`UIFont?`.你需要在创建字典条目之前解开它...但最好不要用`!`(除非崩溃是必需的). (2认同)
  • 有一个非常相似的问题,但有颜色.`NSForegroundColorAttributeName`正在设置一个可选的NSColor(是NS-,在macOS上).预3.0会出错.对一些新的可选处理不太满意. (2认同)