53

在 Objective-C 中,我可以使用:

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

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

有什么帮助吗?

4

6 回答 6

159

我所做的是这样的:

迅捷5.x

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

迅捷4.x

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

迅速 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)])

迅捷 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)])
于 2014-06-10T13:21:48.067 回答
8

只需使用显式转换:

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

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

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

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

于 2014-06-10T13:07:05.243 回答
7

只有一条线的解决方案:

yourLabel.intrinsicContentSize.width用于 Objective-C / Swift

即使您的标签文本具有自定义文本间距,这也将起作用。

于 2018-09-17T04:52:43.197 回答
2

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

var stringToCalculateSize:String = "My text"
var stringSize:CGSize = (stringToCalculateSize as NSString).sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
于 2015-03-26T09:49:38.930 回答
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)
于 2015-04-21T06:26:38.317 回答
-3

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

于 2016-10-19T05:31:56.367 回答