Reputation: 1768
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):
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!!
Upvotes: 0
Views: 140
Reputation: 5858
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}
Upvotes: 2
Reputation: 588
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)
Upvotes: 1
Reputation: 4337
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.
Upvotes: 2