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.
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.
Should use (NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
for options
parameter.
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!
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