Trip
Trip

Reputation: 27124

How to properly get the width of a string in Swift iOS8?

I've read a number of SO posts about this, but couldn't find anything that worked.

My code :

let englishTextSize    = englishString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14)])
let englishLabel       = UILabel(frame: CGRectMake(self.view.center.x, 150, englishTextSize.width, englishTextSize.height))

This code snippet causes an ellipses around my text thus obviating that the width isn't great enough.

The text itself uses a lot of obscure characters like :

svarūpe-'vasthānam

But I can't imagine that throwing it off that much. Open to any tips in Swift or Obj-C though preferably Swift!

Upvotes: 2

Views: 2475

Answers (4)

Bharat Bhushan
Bharat Bhushan

Reputation: 419

Below code works perfectly for me.Hope it will help you as well...

    let name = "Statue of liberty"
    let size = (name as NSString).size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)])

Upvotes: 2

Ro22e0
Ro22e0

Reputation: 394

Depend of the attribute

let englishTextSize = englishString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14)])
let englishLabel = UILabel(frame: CGRectMake(self.view.center.x, 150, englishTextSize.width, englishTextSize.height))

print(englishLabel.text.sizeWithAttributes(orderAttributes).width)

Upvotes: 2

Eiko
Eiko

Reputation: 25632

Your code could be as simple as this:

let englishLabel = UILabel(CGRectZero)
label.text = englishString
label.sizeToFit()
label.center = CGPointMake(self.view.center.x, 150)

Upvotes: 4

Cai
Cai

Reputation: 3659

No need to calculate the width yourself. You can use sizeToFit to make the width and height to fit the text, then change the frame to the height and origin you wanted.

Something like:

[englishLabel sizeToFit];
[parentView addSubview:englishLabel];
englishLabel.center = [parentView convertPoint:parentView.center
                                  fromView:parentView.superview];

Upvotes: 0

Related Questions