NSAttributedString
我可以使用转义的换行符 ( )创建多行@"\n"
。在 iOS 7 中,我现在可以嵌入一个UIImage
内部属性字符串(通过NSTextAttachment
)。
我注意到,每当我将attributedText
a设置UILabel
为带有嵌入图像的多行属性字符串时,实际显示的行数与标签的高度成反比。例如,标签的高度为80时,出现两行;当高度在 100 左右时,只出现第二行;当高度约为 130 时,什么也没有出现。
尝试在 a 内并排放置多个 UILabelUITableViewCell
并让标签随单元格高度(垂直)增长时,会出现此问题。
谁能解释为什么会这样?有谁知道不涉及使 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
...把它放在“单一视图应用程序”的默认视图控制器中。(您可以选择自己的图像。)