【发布时间】:2015-05-16 11:30:44
【问题描述】:
如何设置作为属性字符串附件的模板图像的颜色?
背景:
我有一个 UILabel 并将其属性文本设置为 NSAttributedString。 NSAttributedString 包含一个带有小图像的 NSTextAttachment。现在我想让我的图像颜色与文本颜色匹配,但我不知道如何使它工作。
我通常希望通过将其渲染模式设置为 UIImageRenderingModeAlwaysTemplate 来为图像着色,然后在包含的 UIView 上设置 tintColor。我尝试在我的 UILabel 上设置 tintColor,但没有效果。
这是我的代码。它在 Ruby (RubyMotion) 中,因此语法可能看起来有点滑稽,但它与 Objective C 1:1 映射。
attachment = NSTextAttachment.alloc.initWithData(nil, ofType: nil)
attachment.image = UIImage.imageNamed(icon_name).imageWithRenderingMode(UIImageRenderingModeAlwaysTemplate)
label_string = NSMutableAttributedString.attributedStringWithAttachment(attachment)
label_string.appendAttributedString(NSMutableAttributedString.alloc.initWithString('my text', attributes: { NSFontAttributeName => UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote), NSForegroundColorAttributeName => foreground_color }))
label = UILabel.alloc.initWithFrame(CGRectZero)
label.tintColor = foreground_color
label.attributedText = label_string
label.textAlignment = NSTextAlignmentCenter
label.numberOfLines = 0
【问题讨论】:
-
您是否找到了任何不涉及在将图像添加为文本附件之前绘制图像的答案?我很想有一个简单的方法来做到这一点。
-
很遗憾没有。就我而言,我的字符串有时在深色背景上为白色,有时在浅色背景上为黑色......我最终只是将附件图像更改为适用于两种背景的中性灰色。
标签: ios nsattributedstring nstextattachment