Swift中的CGSize sizeWithAttributes

时间:2014-06-10 12:57:50

标签: ios swift cgsize

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

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

但是在Swift语言中,我没有找到解决这种情况的方法。

任何帮助?

6 个答案:

答案 0 :(得分:138)

我做的是这样的:

swift 4.x

let myString = "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)])

答案 1 :(得分:8)

只需使用显式转换:

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

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

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

This answer至少值得关注,因为它突出了两种方法之间的潜在差异。

答案 2 :(得分:6)

仅一种解决方案:

yourLabel.intrinsicContentSize.width for Objective-C / Swift

即使您的标签文本具有自定义的文本间距,此功能也可以使用。

答案 3 :(得分:3)

您也可以使用这段代码,它更容易,您不必为了获取NSString对象而创建新变量:

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

答案 4 :(得分:1)

在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)

答案 5 :(得分:-3)

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