相关疑难解决方法(0)

使用NSAttributedString更改字符串颜色?

我有一个调查滑块,根据滑块的值显示以下字符串:"非常糟糕,糟糕,好,好,非常好".

以下是滑块的代码:

- (IBAction) sliderValueChanged:(UISlider *)sender {
    scanLabel.text = [NSString stringWithFormat:@" %.f", [sender value]];
    NSArray *texts=[NSArray arrayWithObjects:@"Very Bad", @"Bad", @"Okay", @"Good", @"Very Good", @"Very Good", nil];
    NSInteger sliderValue=[sender value]; //make the slider value in given range integer one.
    self.scanLabel.text=[texts objectAtIndex:sliderValue];
}
Run Code Online (Sandbox Code Playgroud)

我希望"非常糟糕"为红色,"坏"为橙色,"好"为黄色,"好"和"非常好"为绿色.

我不明白如何使用NSAttributedString来完成这项工作.

cocoa-touch nsattributedstring ios

137
推荐指数
7
解决办法
15万
查看次数

如何在NSTextAttachment中设置模板化图像的颜色

如何设置作为属性字符串附件的模板化图像的颜色?

背景:

我有一个UILabel,我将其attributionText设置为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
Run Code Online (Sandbox Code Playgroud)

nsattributedstring nstextattachment ios

24
推荐指数
4
解决办法
6622
查看次数