在Objective-C中,我能够使用:
CGSize stringsize =
[strLocalTelefone sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}];
但是在Swift语言中,我没有找到任何解决这种情况的方法。
可以帮忙吗?
在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)])
let size: CGSize = myString.sizeWithAttributes([NSFontAttributeName: UIFont(name: "Helvetica", size: 15.0)!])
对我来说没有问题,我不确定你卡在哪里了。 - holexString
完全支持Unicode字符,因此没有任何区别。 - holex只需使用显式转换:
var stringsize = (strLocalTelefone as NSString).sizeWithAtt...
var strLocalTelefone = "some string"
var stringsize = strLocalTelefone.bridgeToObjectiveC().sizeWithAttributes([NSFontAttributeName:UIFont.systemFontOfSize(14.0)])
这篇答案值得一看,因为它突出了两种方法之间的潜在差异。
String
无缝桥接到 NSString
。 - BillsizeWithAttributes
,而不是创建一个带名称的新常量(如所接受的答案中所示)。这样可以减少代码量,并且基本上做相同的事情(因为桥接会给您一个 NSString
)。因此,我认为创建一个新的命名常量是不必要的。 - FirotitleLabel
:self.myButton.titleLabel.text
。这是你要找的吗? - Firo仅需一行代码:
yourLabel.intrinsicContentSize.width
对于Objective-C / Swift
即使您的标签文本具有自定义文本间距,此方法也适用。
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)
let dict = [NSFontAttributeName:UIFont(name: "Helvetica Neue", size: 14.0)!]
呢? - Aaron Brager