Does anyone know of a work around or what I am currently doing wrong here.
CGSize boundingSize = CGSizeMake(288, 9999);
CGRect boundingRect = [text boundingRectWithSize:boundingSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObjectsAndKeys:theFont, NSFontAttributeName, nil]
context:nil];
When the code runs on iOS7 (both on the phone and sim) the size returned is 416.3 wide with a height of 15.5. Clearly the boundingRectWithSize is just being ignored. Has anyone else come across this and if so has anyone an idea on how to fix it or can someone point me to where I am going wrong.
As per the Apple documentation:
You can use this method to compute the space required to draw the string. The constraints you specify in the size parameter are a guide for the renderer for how to size the string. However, the actual bounding rectangle returned by this method can be larger than the constraints if additional space is needed to render the entire string. Typically, the renderer preserves the width constraint and adjusts the height constraint as needed.
If you specify a fixed font and too small a space, something has to give. In this case, it's the bounding space. I'm guessing you expected line wrapping. Does a width of 288 allow any reasonable wraps?
I knows that this is old question, but I found a workaround for your problem. below is the code example
1) First create a macro for minimum height
#define MIN_HEIGHT 10.0f
2) After that use below code to give variable height based on your text specified. But for this you need to specify the frame for UILabel OR whatever you are using for displaying the text.
// Initialize UILabel with initial frame.
UILabel *lblMakeModel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 180, 50)];
// Set numberOfLines as zero
lblMakeModel.numberOfLines = 0;
// Set text here
lblMakeModel.text = @"sdbsbdjhsbdhjsbdhjasd bhbdhjasbdsahjdbahjsdbjhsd bdhjsabdhjsbdhsbdhsad dhbsadbasdhbsajhdbsadyogi";
// create a constraint for fixed width and maximum 20000 height.
CGSize constraint = CGSizeMake(lblMakeModel.frame.size.width, 20000.0f);
// Get the CGRect with the given constraint for the text of UILabel
CGRect textRect = [lblMakeModel.text boundingRectWithSize:constraint
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName:lblMakeModel.font}
context:nil];
// Set LineBreakMode for UIlabel
[lblMakeModel setLineBreakMode:NSLineBreakByWordWrapping];
[lblMakeModel setAdjustsFontSizeToFitWidth:NO];
// Again set the frame from the height you get from CGRect object.
[lblMakeModel setFrame:CGRectMake(lblMakeModel.frame.origin.x, lblMakeModel.frame.origin.y, lblMakeModel.frame.size.width, MAX(textRect.size.height, MIN_HEIGHT))];
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