我可以使用转义换行符 (@"\n"
) 创建多行 NSAttributedString
。在 iOS 7 中,我现在可以在属性字符串中嵌入一个 UIImage
(通过 NSTextAttachment
)。
我注意到,每当我将 UILabel
的 attributedText
设置为带有嵌入图像的多行属性字符串时,实际显示的行数是 与标签的高度成反比。比如当标签的高度为80时,出现两条线;当高度在100左右时,只出现第二行;当高度为130左右时,什么也没有出现。
当尝试在 UITableViewCell
中并排放置多个 UILabel 并让标签随着单元格高度(垂直)增长时,会出现此问题。
谁能解释为什么会这样?有谁知道不涉及缩小 UILabel 的解决方法?
示例代码:
@implementation SOViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableAttributedString *text1 = [[NSMutableAttributedString alloc] init];
[text1 appendAttributedString:[[NSAttributedString alloc] initWithString:@"Line 1\n"]];
[text1 appendAttributedString:[[NSAttributedString alloc] initWithString:@"Line 2"]];
UIImage *image = [UIImage imageNamed:@"17x10"]; //some PNG image (17px by 10px)
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = image;
attachment.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
NSMutableAttributedString *text2 = [[NSMutableAttributedString alloc] init];
[text2 appendAttributedString:[[NSAttributedString alloc] initWithString:@"Line 1\n"]];
[text2 appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
[text2 appendAttributedString:[[NSAttributedString alloc] initWithString:@"Line 2"]];
CGFloat margin = 20;
//shows both lines when height == 80
//shows line 2 when 90 <= height <= 120
//shows nothing when height == 130
CGFloat height = ???;
CGFloat width = 200;
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(margin, margin, width, height)];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(margin, margin + height, width, height)];
[self.view addSubview:label1];
[self.view addSubview:label2];
label1.backgroundColor = [UIColor orangeColor];
label2.backgroundColor = [UIColor blueColor];
label2.textColor = [UIColor whiteColor];
label1.numberOfLines = 0;
label2.numberOfLines = 0;
label1.attributedText = text1;
label2.attributedText = text2;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(margin + width, margin + height, image.size.width, image.size.height);
[self.view addSubview:imageView];
}
@end
...将它放在“单 View 应用程序”的默认 View Controller 中。 (您可以选择自己的图片。)
最佳答案
它确实与 NSTextAttachment 无关。到目前为止,在 iOS 7 中,UILabel 不太擅长绘制属性字符串。带有一些下划线和居中段落样式的简单属性字符串将在 UILabel 中显示为空白或部分空白;相同的属性字符串在 UITextView 中绘制得很好。
因此,目前的一种解决方案是:改用 UITextView。这实际上是一个非常好的解决方案,因为在 iOS 7 中,UITextView 只是 Text Kit 堆栈的包装器。所以它以一种直接的方式绘制属性字符串。它不会受到它在以前的 iOS 版本中与 Web Kit 的底层关系的阻碍。
另一方面,我也找到了解决这个 UILabel 错误的方法;您必须摆弄标签的行数和字符串,以便将文本塞到标签的顶部:在这里查看我的答案 - https://stackoverflow.com/a/19409962/341994
或者您可以等待 Apple 修复该错误并祈祷。编辑:在 iOS 7.1 中,该错误似乎将被修复并且不需要解决方法。
关于ios - 嵌入 NSTextAttachment 时高 UILabel 中缺少的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19253224/