How to calculate the height of the text rectangle from an NSString?

。_饼干妹妹 提交于 2019-12-03 07:52:54

Sounds like after you get the actual font size from that function call, you need to call again with that new size:

NSString* yourString = @"SomeString";
float actualSize;
[yourString sizeWithFont:yourFont 
             minFontSize:minSize 
          actualFontSize:&actualSize 
                forWidth:rectWidth 
           lineBreakMode:breakMode];

CGSize size = [yourString sizeWithFont:[UIFont fontWithName:fontName size:actualSize]];
nevan king

Try this code:

CGSize maximumSize = CGSizeMake(300, 9999);
NSString *myString = @"This is a long string which wraps";
UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize myStringSize = [myString sizeWithFont:myFont 
    constrainedToSize:maximumSize 
    lineBreakMode:self.myLabel.lineBreakMode];

from my answer here

It uses a different method, and sets up a very high CGSize at the start (which is then shrunk to fit the string)

Important: As of iOS 7.0 the following method is deprecated.

sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:

Use the below code instead

CGRect frame = [cellText boundingRectWithSize:CGSizeMake(568,320) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:32.0f]} context:nil];
float height = frame.size.height;

Also have you set label.numberOfLines = 0; ?

After running this code frame.size will have the height and width of your nsstring exactly..

NSString *text = @"This is my Mac";
textFont = [NSFont fontWithName:@"HelveticaNeue-Medium" size: 80.f];
textColor = [NSColor yellowColor];
NSDictionary *attribs = @{ NSForegroundColorAttributeName:textColor,
                           NSFontAttributeName: textFont };
CGRect frame = [text boundingRectWithSize:CGSizeMake(0,0) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesDeviceMetrics attributes:attribs context:nil];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!