iOS NSTextAttachment图像未显示

sho*_*_sm 2 nsattributedstring nstextattachment ios

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];
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当边缘附近的文本时,锁图标丢失了.

当边缘附近的文本时,锁图标丢失了.

Sco*_*Zhu 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];
Run Code Online (Sandbox Code Playgroud)

通过检查我的帖子附加星星到UILabel的末尾,查看有关我的解决方案的更多信息.