iOS NSTextAttachment 图像未显示

Posted

技术标签:

【中文标题】iOS NSTextAttachment 图像未显示【英文标题】:iOS NSTextAttachment image not showing 【发布时间】:2014-08-14 06:27:36 【问题描述】:

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

当文字靠近边缘时,锁图标不见了。

【问题讨论】:

在顶部图像中,文本也一直到最后,但它显示图像.. @iDev 图片不显示。 但是如果你看到两个文本是一样的 @iDev 文字不一样。我添加了更多单词,以便文本不会停在边缘,从而显示图像。 移除sizeToFit()并改变高度 【参考方案1】:

只需在 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];
/** 
 * 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,了解有关我的解决方案的更多信息。

【讨论】:

我有一个类似的错误,如果文本附件靠近边缘,它会消失。添加空格触发新行。 谢谢,我遇到了同样的问题,您的解决方案可能为我节省了几个小时!

以上是关于iOS NSTextAttachment 图像未显示的主要内容,如果未能解决你的问题,请参考以下文章

即使在主队列中,更改 NSTextAttachment 图像也不会立即起作用

NSTextAttachment 未显示在今日通知中心小部件中

ios7自定义与uilabel中的nstextattachment交互

如何将菜单选项添加到 NSTextAttachment 弹出菜单是 UITextView?

NSTextAttachment 使用 textkit 时覆盖文本

如何禁用 NSTextAttachment 上的交互?