我无法让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();
答案 0 :(得分:0)
我明白了。问题出在[UIImage imageNamed:@"ContestTokenSmall"]
上。由于图像位于此代码所在的框架中,我需要使用
+ (nullable UIImage *)imageNamed:(NSString *)name inBundle:(nullable NSBundle *)bundle compatibleWithTraitCollection:(nullable UITraitCollection *)traitCollection NS_AVAILABLE_IOS(8_0);
这样它就可以从正确的包中获取图像。我在调试时从框架的包中获取图像,这就是图像在图像视图中显示而不显示在属性字符串中的原因。