manili
manili

Reputation: 618

Swift: Getting a string width to make a frame (using CGRect) in swift 2.2

How can I get width of a string in swift 2.2 and iOS 9 ?
What I want to do is to create a UIButton programmatically but its frame needs to fit the title size which will be inferred at runtime.
Note: We know frame's height.

Upvotes: 0

Views: 3817

Answers (4)

ff10
ff10

Reputation: 3147

You might want to use the NSString method boundingRectWithSize:options:attributes:context:.

e.g.:

let rectNeeded = aString.boundingRectWithSize(CGSize(width: yourWidth, height: yourHeight), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: aFont!], context: nil)

Note that you need to cast you String into an NSString before being able to use this method.

Upvotes: 1

matt
matt

Reputation: 535315

Don't use frames. Use auto layout. If you use auto layout to place this button into the interface, it will be sized to fit its text automatically.

Upvotes: 0

Santosh
Santosh

Reputation: 2914

You can get the size by declaring your button title text as NSString. Try this:

let title: NSString = "some title"
let size = title.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(20.0)]) //you can add NSForegroundColorAttributeName as well

Upvotes: 3

Dravidian
Dravidian

Reputation: 9945

After you have set the text of button just call :-

yourButton.sizeToFit()

Upvotes: 3

Related Questions