在 Objective-C 中,我可以使用:
CGSize stringsize =
[strLocalTelefone sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}];
但是在 Swift 语言中,我没有找到任何解决这种情况的方法。
有什么帮助吗?
我所做的是这样的:
let myString = "Some text is just here..."
let size: CGSize = myString.size(withAttributes: [.font: UIFont.systemFont(ofSize: 14)])
let myString = "Some text is just here..."
let size: CGSize = myString.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)])
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)])
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 的更高版本不再支持桥接。
var strLocalTelefone = "some string"
var stringsize = strLocalTelefone.bridgeToObjectiveC().sizeWithAttributes([NSFontAttributeName:UIFont.systemFontOfSize(14.0)])
这个答案至少值得一看,因为它突出了两种方法之间的潜在差异。
只有一条线的解决方案:
yourLabel.intrinsicContentSize.width
用于 Objective-C / Swift
即使您的标签文本具有自定义文本间距,这也将起作用。
您也可以使用这段代码,它更容易,您不必为了获取 NSString 对象而创建新变量:
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)])