how-to-get-the-width-of-an-nsstring
Hi David -
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; }
_
Send the string a sizeWithAttributes: message, passing a dictionary containing the attributes with which you want to measure the string.
_
By "width" do you mean the number of characters in the string?
NSUInteger len = [myString length];
NSString docs
_
Sorry my question was not detailed enough and is not exactly what I'm trying to do. I am using a text storage, layout manager and a text container. The solution is to use the layout manager to determine the rectangle that bounds the rect. Here is the code.
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:@"hello"];NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];NSTextContainer *textContainer = [[NSTextContainer alloc] init];[layoutManager addTextContainer:textContainer];[textContainer release];[textStorage addLayoutManager:layoutManager];[layoutManager release];//Figure out the bounding rectangleNSRect stringRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(0, [layoutManager numberOfGlyphs]) inTextContainer:textContainer];
_
UIKit has a nice addition to NSString, making sizeWithAttributes: a bit lighter:
CGSize titleSize = [title sizeWithFont:titleFont constrainedToSize:contentCellSize lineBreakMode:UILineBreakModeWordWrap];
posted on 2014-03-18 11:55 MoreNotepad++ 阅读(187) 评论(0) 收藏 举报
浙公网安备 33010602011771号