Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the width of an NSString?

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

Thanks.

like image 519
David Avatar asked Aug 07 '10 08:08

David


People also ask

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

Do I need to release NSString?

If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.


1 Answers

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;  } 
like image 173
Stephen Poletto Avatar answered Oct 09 '22 03:10

Stephen Poletto