I am trying to get the width of an NSString (ex. NSString *myString = @"hello"). Is there a way to do this?
Thanks.
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With