Swift 3错误:无法识别的select器发送到实例

我只是将我们的项目迁移到swift 3,并且因为一个问题而看到很多崩溃:

由于未捕获的exception“NSInvalidArgumentException”而终止应用程序,原因:' – [_ SwiftValue pointSize]:无法识别的select器已发送到实例

这个错误的原因是呼吁:

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

我注意到的是,如果我把String转换成NSString并调用boundingRectWithSize就会抛出这个错误。 这似乎也发生在许多其他部分,例如,如果我在故事板中发送视图控制器标题,它会引发同样的错误。

任何人都有同样的问题?

重现问题:

在Xcode 8中创build一个新的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) 

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

如果我使用你的testing代码,但让attributes的数据types为默认的,它不会崩溃。 那是:

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

点击该variables的选项说是[String : UIFont]

多一点testing,表明它与可选对象有关; [String: AnyObject]似乎工作正常。

编辑:毕竟,我决定阅读文件,其中说,使用[String: Any] 。 🙂

以下为我解决了这个问题:

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

用[String:Any]replaceNSDictionary将解决这个问题。 let attributes: [String: Any] = [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,blue:42 / 255.0,alpha:1.0 ))