In objective-C I was able to use:
CGSize stringsize =
[strLocalTelefone sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}];
But in Swift Language I didn't found any solution for this situation.
Any Help?
what I did is something like this:
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)])
Just use explicit casting:
var stringsize = (strLocalTelefone as NSString).sizeWithAtt...
Otherwise you can bridge it too:
Bridging is no longer supported in later versions of Swift.
var strLocalTelefone = "some string"
var stringsize = strLocalTelefone.bridgeToObjectiveC().sizeWithAttributes([NSFontAttributeName:UIFont.systemFontOfSize(14.0)])
This answer is worth at least looking at, as it highlights potential differences between the two approaches.
Just one line solution:
yourLabel.intrinsicContentSize.width
for Objective-C / Swift
This will work even your label text have custom text spacing.
You can also use this piece of code, it's easier and you don't have to create new variable just to get NSString object:
var stringToCalculateSize:String = "My text"
var stringSize:CGSize = (stringToCalculateSize as NSString).sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With