iOS NSTextAttachment图像未显示

时间:2014-08-14 06:27:37

标签: ios nsattributedstring nstextattachment

NSTextAttachment锁定图像在边缘切断,但当线条没有在边缘处断开时,可以看到锁定图标。我希望图标移动到下一行,就像一个单词移动到下一行。

以下是示例:

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:@"lock.png"];
    NSString *stringHeadline = @"This is a example sample sentence. Why I do";
    NSAttributedString *attachmentLock = [NSAttributedString attributedStringWithAttachment:attachment];
    NSAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:stringHeadline];
    NSMutableAttributedString *lockString = [[NSMutableAttributedString alloc] initWithAttributedString:myText];

    [lockString appendAttributedString:attachmentLock];
    lblHeadline.attributedText = lockString;
    [lblHeadline sizeToFit];

enter image description here

Lock icon gone missing when the text near the edge.

边缘附近的文字时,锁定图标丢失了。

1 个答案:

答案 0 :(得分:6)

在NSTextAttachment之后添加一个空格。否则,当没有足够的空间时,NSTextAttachment不会像普通文本那样更改为新行。我相信这是Apple的一个错误。

您的代码应该是这样的:

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"lock.png"];
NSString *stringHeadline = @"This is a example sample sentence. Why I do";
NSAttributedString *attachmentLock = [NSAttributedString attributedStringWithAttachment:attachment];
NSAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:stringHeadline];
NSMutableAttributedString *lockString = [[NSMutableAttributedString alloc] initWithAttributedString:myText];

[lockString appendAttributedString:attachmentLock];
/** 
 * Here I'm adding a space after NSTextAttachment just to make sure that
 * the NSTextAttachment will auto change to next line like normal text does.
 * Otherwise the NSTextAttachment does not move to the new line.
 */
[lockString appendAttributedString: [[NSAttributedString alloc] initWithString:@" "]];
lblHeadline.attributedText = lockString;
[lblHeadline sizeToFit];

查看我的帖子Attach Stars to the End of a UILabel,了解有关我的解决方案的更多信息。