NSTextAttachment 不显示

NSTextAttachment not showing

我无法让 NSTextAttachment 显示下面函数返回的 NSAttributedString

- (NSAttributedString *) tokenString:(NSUInteger) tokens
{
CGFloat size = 20;
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.bounds = CGRectMake(0,0,size,size)
attachment.image = [[UIImage imageNamed:@"ContestTokenSmall"] imageScaledToSize:CGSizeMake(size, size)];

NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" %ld", (long)tokens] attributes:[self attributedStringAttributes]];
[str insertAttributedString:attachmentString atIndex:0];
return str;
}

我使用的标签如下:

- (UILabel *) tokenLabel
{
if (_tokenLabel == nil)
{
    _tokenLabel = [[UILabel alloc] init];
    _tokenLabel.translatesAutoresizingMaskIntoConstraints = NO;
    _tokenLabel.font = [UIFont zbd_boldFontWithSize:13.0];
    _tokenLabel.textColor = UIColor.whiteColor;
    [_tokenLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
    [_tokenLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    [_tokenLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
    [_tokenLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
}
return _tokenLabel;
}

我试过删除 NSTextAttachment 边界,changing/removing 调整图像大小,并使用不同的图像,但我似乎没有做任何事情使图像出现在标签中。

上面的代码有问题吗?是否需要在标签中设置属性才能显示图片?

提前致谢!

编辑

我如何设置标签:

self.tokenLabel.attributedText = [self tokenString:award.topBid];

字符串日志:

2018-04-24 16:03:14.579429-0500 TestGame1[44243:1597097] {
    NSAttachment = "<NSTextAttachment: 0x6040002c2e60>";
} 10{
    NSColor = "UIExtendedGrayColorSpace 1 1";
    NSFont = "<UICTFont: 0x7ff0df85ff10> font-family: \"Domus\"; font-weight: bold; font-style: normal; font-size: 13.00pt";
}

此外,我在应该放置图像的地方看到一个空 space。

更新 2

使用以下代码创建的图像将显示在属性字符串中,但从 Media.xcassets 加载的 pdf 或 png 图像中的 none 仍然会显示。

CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor.redColor CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

我明白了。问题出在 [UIImage imageNamed:@"ContestTokenSmall"]。由于图像位于此代码所在的框架中,因此我需要使用

+ (nullable UIImage *)imageNamed:(NSString *)name inBundle:(nullable NSBundle *)bundle compatibleWithTraitCollection:(nullable UITraitCollection *)traitCollection NS_AVAILABLE_IOS(8_0);

这样它就可以从正确的包中获取图像。我在调试时从框架的包中获取图像,这就是为什么图像会显示在图像视图中而不显示在属性字符串中的原因。