Swift 3 error: [_SwiftValue pointSize] unrecognized selector sent to instance

Swift 3 error: [_SwiftValue pointSize] unrecognized selector sent to instance

我刚刚将我们的项目迁移到 swift 3,但由于一个问题导致了很多崩溃:

由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'-[_SwiftValue pointSize]:无法识别的选择器发送到实例

该错误的原因是调用:

[NSAttributedString(NSExtendedStringDrawing) boundingRectWithSize:options:context:]

我注意到,如果我将 String 转换为 NSString 并对其调用 boundingRectWithSize,它会抛出该错误。它似乎也发生在许多其他部分,例如,如果我在情节提要中发送视图控制器标题,它会抛出相同的错误。

有人遇到同样的问题吗?

重现问题:

在Xcode8中新建一个Swift3项目,并在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)

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

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

let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 14)]

按住 Option 键单击变量表示它是 [String : UIFont]

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

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

以下为我修复了它:

let attributes: [String: UIFont] = [NSFontAttributeName: UIFont.systemFont(ofSize: 14)]
func attributedString(firstText : String, amount : String, fontSize : CGFloat, color : UIColor) -> NSAttributedString {

    let attrDict = [ NSFontAttributeName : UIFont(name: fontRegular, size: CGFloat(fontSize/2))!,
                    NSForegroundColorAttributeName : UIColor.darkGray] as [String : AnyObject]
    let iconString = NSMutableAttributedString(string: firstText, attributes: attrDict)

    let attrDict1 = [ NSFontAttributeName : UIFont(name: fontRegular, size: CGFloat(fontSize))!,
                     NSForegroundColorAttributeName : color] as [String : AnyObject]
    let amountString = NSMutableAttributedString(string: amount, attributes: attrDict1)

    iconString.append(amountString)
    return iconString
}

然后这样称呼它

lblBalanceAmount.attributedText = self.attributedString(firstText: "My Balance", amount: "500", fontSize: newFontSize, color: UIColor(red: 41/255.0, green: 192/255.0 , 蓝色: 42/255.0, 阿尔法: 1.0))