How to get the width of an NSString?

33,790

Solution 1

Here's a relatively simple approach. Just create an NSAttributedString with the appropriate font and ask for its size:

- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
     NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
     return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
 }

Solution 2

UIFont * font = [UIFont systemFontOfSize:15];

CGSize stringSize = [aString sizeWithFont:font]; 

CGFloat width = stringSize.width;

Solution 3

Using the UILabel's attributed string:

- (CGSize)getStringSizeWithText:(NSString *)string font:(UIFont *)font{

    UILabel *label = [[UILabel alloc] init];
    label.text = string;
    label.font = font;

    return label.attributedText.size;
}

Solution 4

i dont know if you are suppose to use this in cocoa touch. if it is, then:

- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
     NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
     return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
 }

wont work.

in cocoa touch, you gotta add coretext framework and import the header and write your code like this:

UIFont *font = [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:DEFAULT_FONT_SIZE];
//    NSLog(@"%@", NSFontAttributeName);
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, (NSString     *)kCTFontAttributeName, nil];

but, GEE!!!!!

NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:self.caption attributes:attributes];
[as size].width;

there's no size this method in NSMutableAttributedString!

finally, this would work

[self.caption sizeWithFont:font].width

Solution 5

Send the string a sizeWithAttributes: message, passing a dictionary containing the attributes with which you want to measure the string.

Share:
33,790
David
Author by

David

Updated on July 09, 2022

Comments

  • David
    David almost 2 years

    I am trying to get the width of an NSString (ex. NSString *myString = @"hello"). Is there a way to do this?

    Thanks.