我可以使用转义换行符 (@"\n"
) 创建一个多行的 NSAttributedString
。在 iOS 7 中,我现在可以通过 NSTextAttachment
在属性字符串中嵌入一个 UIImage
。
我注意到,每当我将一个带有嵌入图像的多行属性字符串设置为 UILabel
的 attributedText
时,实际显示的行数与标签高度成反比例关系。例如,当标签的高度为80时,会显示两行;当高度约为100时,只显示第二行;当高度约为130时,则什么也不显示。
这个问题出现在试图在 UITableViewCell
中侧边放置多个 UILabels
并使标签 (纵向) 随单元格高度增长时。
有人能解释这是为什么吗?有没有不需要使 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
...将此代码放入“单视图应用程序”的默认视图控制器中。(您可以选择自己的图像。)