iOS NSTextAttachment 图片未显示

4

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];

在边缘附近的文本中锁图标丢失了

当文本靠近边缘时,锁图标会丢失。


在顶部的图片中,文本一直延伸到末尾,但它显示为图像。 - Rajesh
@iDev 图片无法显示。 - shoujo_sm
@iDev 这些文本不一样。我添加了更多的单词,以便文本不会停在边缘,从而显示图像。 - shoujo_sm
删除 sizeToFit() 并更改高度。 - Rajesh
我的标签高度是动态的,如果标题句子很长,它会自动扩展。移除 sizeToFit 将使其变为静态。 - shoujo_sm
显示剩余2条评论
1个回答

7

在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];

如果你想了解更多关于我的解决方案的内容,可以查看我发布的文章"在UILabel末尾添加星号"


我曾经遇到一个类似的 bug,当文本附件靠近边缘时它会消失。加上一个空格会触发新的一行。 - Edwin
谢谢,我遇到了同样的问题,你的解决方案节省了我几个小时的时间! - Alexander Tkachenko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接