我创建一个 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];
然后我获取它的大小以与按钮一起使用并将其添加到 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
现在比应有的要短一些,因为它不尊重文本视图换行。
你可以告诉boundingRectWithSize
以自动换行模式处理字符串。你必须添加一个NSParagraphStyle
attribute 到 attribute 参数,其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];
然后使用attr
作为属性参数boundingRectWithSize
.
您可以轻松扩展/推广此技术,以从任何有意义的来源读取其他属性,包括现有的段落样式属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)