CGSize sizeWithAttributes在Swift中

在Objective-C中,我能够使用:

CGSize stringsize = [strLocalTelefone sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}]; 

但在Swift语言中,我没有find任何解决scheme。

任何帮助?

我所做的是这样的:

Swift 4(testing版)

 let myString: String = "Some text is just here..." let size: CGSize = myString.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14.0)]) 

Swift 3

 var originalString: String = "Some text is just here..." let myString: NSString = originalString as NSString let size: CGSize = myString.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)]) 

Swift 2.x

 var originalString: String = "Some text is just here..." let myString: NSString = originalString as NSString let size: CGSize = myString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)]) 

只要使用显式的投射:

 var stringsize = (strLocalTelefone as NSString).sizeWithAtt... 

否则,你可以桥接它:
在更高版本的Swift中不再支持Bridging。

 var strLocalTelefone = "some string" var stringsize = strLocalTelefone.bridgeToObjectiveC().sizeWithAttributes([NSFontAttributeName:UIFont.systemFontOfSize(14.0)]) 

这个答案至less值得一看,因为它突出了两种方法之间的潜在差异。

你也可以使用这段代码,这很容易,你不必为了得到NSString对象而创build新的variables:

 var stringToCalculateSize:String = "My text" var stringSize:CGSize = (stringToCalculateSize as NSString).sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)]) 

在xCode 6.3上,这是你现在需要做的事情:

  let font:AnyObject = UIFont(name: "Helvetica Neue", size: 14.0) as! AnyObject let name:NSObject = NSFontAttributeName as NSObject let dict = [name:font] let textSize: CGSize = text.sizeWithAttributes(dict) 

在xCode 8.0上,这是你现在需要做的:let charSize = string.size(attributes:[NSFontAttributeName:UIFont.systemFont(ofSize:20)])