本文介绍了boundingRectWithSize不遵守自动换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个UITextView,向其中添加文本,然后将其放入视图中(带有容器)

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];

然后我获得它的大小以供按钮使用,并将其添加到UITextView

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];

这在大多数情况下有效.这会尊重\ n换行符(就像我在stringWithFormat中添加的一样),但不会尊重文本视图自动添加的自动换行.因此,如果lyrics的行在屏幕上不适合显示,则UITextView会对其进行换行(按理应如此),但是size现在比它应该的短一些,因为它不遵守文本视图换行

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.

推荐答案

进行了更多研究,最终找到了.

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!

这篇关于boundingRectWithSize不遵守自动换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!