Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boundingRectWithSize does not respect word wrapping

I create a UITextView, add text to it, and put it in the view (with a container)

UITextView *lyricView = [[UITextView alloc] initWithFrame:screen];
lyricView.text = [NSString stringWithFormat:@"\n\n%@\n\n\n\n\n\n", lyrics];
[container addSubview:lyricView];
[self.view addSubview:container];

I then get the size of it for use with a button and add it to the UITextView

CGRect size = [lyrics boundingRectWithSize:CGSizeMake(lyricView.frame.size.width, MAXFLOAT)
                                 options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:@{NSFontAttributeName:[lyricView font]}
                                 context:nil];
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[doneButton setFrame:CGRectMake(56, size.size.height + 55, 208, 44)];
[doneButton setTitle:@"Done" forState:UIControlStateNormal];
[lyricView addSubview:doneButton];

This works in most cases. This will respect \n line breaks (like I added in my stringWithFormat) but it will not respect word wraps automatically added by the text view. So if lyrics has a line that doesn't fit on the screen, the UITextView will wrap it (as it's supposed to), but size is now slightly shorter than it should be because it did not respect the text view wrap.

like image 827
vqdave Avatar asked Dec 16 '13 02:12

vqdave


3 Answers

You can tell boundingRectWithSize to process the string in word-wrapping mode. You have to add an NSParagraphStyle attribute to the attributes parameter, with its lineBreakMode set to NSLineBreakByWordWrapping. So:

NSMutableDictionary *attr = [NSMutableDictionary dictionary];     
// ...whatever other attributes you need...
NSMutableParagraphStyle *paraStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paraStyle.lineBreakMode = NSLineBreakByWordWrapping;
[attr setObject:paraStyle forKey:NSParagraphStyleAttributeName];

then use attr as the attributes argument to boundingRectWithSize.

You can easily extend/generalise this technique to read other attributes including existing paragraph style attributes from whatever source makes sense.

like image 171
JulianSymes Avatar answered Nov 10 '22 14:11

JulianSymes


Should use (NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) for options parameter.

like image 42
samthui7 Avatar answered Nov 10 '22 14:11

samthui7


Did some more research and ended up finding this.

CGSize textSize = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, FLT_MAX)];
CGFloat textHeight = textSize.height;

Hope this helps someone out there!

like image 3
vqdave Avatar answered Nov 10 '22 14:11

vqdave