boundingRectWithSize不尊重自动换行

vqd*_*ave 10 frame uitextview ios

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

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];
Run Code Online (Sandbox Code Playgroud)

然后我获得它的大小以便与按钮一起使用并将其添加到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];
Run Code Online (Sandbox Code Playgroud)

这适用于大多数情况.这将遵循\n换行符(就像我在stringWithFormat中添加的那样),但它不会尊重由文本视图自动添加的自动换行.因此,如果lyrics有一个不适合屏幕的行,UITextView将包装它(正如它应该的那样),但size现在比它应该略短,因为它不尊重文本视图包装.

Jul*_*mes 6

您可以告诉boundingRectWithSize在自动换行模式下处理字符串.您必须向NSParagraphStyleattributes参数添加属性,并将其lineBreakMode设置为NSLineBreakByWordWrapping.所以:

NSMutableDictionary *attr = [NSMutableDictionary dictionary];     
// ...whatever other attributes you need...
NSMutableParagraphStyle *paraStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paraStyle.lineBreakMode = NSLineBreakByWordWrapping;
[attr setObject:paraStyle forKey:NSParagraphStyleAttributeName];
Run Code Online (Sandbox Code Playgroud)

然后attr用作属性参数boundingRectWithSize.

您可以轻松扩展/概括此技术以从任何有意义的源中读取其他属性,包括现有段落样式属性.

  • 这是无效的,因为它是默认设置 (2认同)
  • 事实上这对我来说也不起作用!在某些情况下,一个单词会被分成两部分并放在两行中...... (2认同)

sam*_*ui7 6

应该(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)用于options参数.


vqd*_*ave 3

做了更多研究并最终发现了这一点

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

希望这对那里的人有帮助!