我无法在下面的函数中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边界、更改/删除图像大小调整以及使用不同的图像,但我所做的一切似乎都没有使图像出现在标签中。
上面的代码有问题吗?我需要在标签中设置一个属性来显示图像吗?
提前致谢!
编辑
我如何设置标签:
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";
}
另外,我看到图像应该是一个空白区域。
更新 2
使用以下代码创建的图像将显示在属性字符串中,但仍然不会显示从 Media.xcassets 加载的 pdf 或 png 图像。
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();