boundingRectWithSize does not respect word wrapping

牧云@^-^@ 提交于 2020-01-02 01:11:51

问题


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.


回答1:


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.




回答2:


Should use (NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) for options parameter.




回答3:


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!



来源:https://stackoverflow.com/questions/20602491/boundingrectwithsize-does-not-respect-word-wrapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!