0

I want to get the width of a String, and I get the answer which is use this method( but it is just in OC): enter image description here

I find it in Official API Document. Of course there is no Swift version. Due to I know nothing about OC, I can't write all my code with OC language. But I find out that I can create a XXX-Bridging-Header.h file, and import the header files of OC that I want to use in .swift File.

However I don't know which header file is this function in. I hope someone could tell me the file name OR point out another way to get the width of String.

Fairly Appreciate!!

Microos
  • 1,618
  • 3
  • 15
  • 32

3 Answers3

2

The sizeWithFont:forWidth:lineBreakMode: method was deprecated in iOS 7.0.

The replacement is boundingRectWithSize:options:attributes:context: and is available from Swift.

Here is a usage example:

let myString = "Hello World" as NSString
let width = 100.0 as CGFloat
let height = 40.0 as CGFloat
let maxSize = CGSizeMake(width, height)
let options: NSStringDrawingOptions  = [.TruncatesLastVisibleLine, .UsesLineFragmentOrigin]
let attr = [ NSFontAttributeName : UIFont.systemFontOfSize(17) ]
let labelBounds = myString.boundingRectWithSize(maxSize, options: options, attributes: attr, context: nil)

The result is in labelBounds as a CGRect. For this example, it is

{x 0 y 0 w 88.312 h 20.287}
Daniel Zhang
  • 5,539
  • 2
  • 21
  • 27
2

The function you want deprecated and it Replace by:

CGRect textRect = [text boundingRectWithSize:size
                           options:NSStringDrawingUsesLineFragmentOrigin
                          attributes:@{NSFontAttributeName:FONT}
                             context:nil];

You can set size:

CGSize size = textRect.size;

In Swift:

 NSString(string).boundingRectWithSize(CGSize(width, DBL_MAX),
                                      options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                                      attributes: [NSFontAttributeName: FONT],
                                      context: nil)

FONT is the font you want.

vien vu
  • 4,049
  • 1
  • 15
  • 30
1

Search the api documentation and you will find: NSString.

As you can see it's in NSString so you don't need to add it to the bridging header. Swift does toll-free bridging between swift strings and NSString however, this method is deprecated so you might have to use a NSString explicitly (not recommended)

barksten
  • 578
  • 4
  • 12
  • Thank you @barksten ! I think this is the exact reason why there is no code hints pop out when I input "size...."! :D Thx a lot! – Microos Oct 29 '15 at 09:08