使用NSAttributedString更改字符串颜色?

Ada*_*dam 137 cocoa-touch nsattributedstring ios

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

以下是滑块的代码:

- (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来完成这项工作.

rma*_*ddy 189

没有必要使用NSAttributedString.你需要的只是一个简单的标签textColor.此外,这个简单的解决方案适用于所有版本的iOS,而不仅仅是iOS 6.

但如果您不必要地使用NSAttributedString,您可以这样做:

UIColor *color = [UIColor redColor]; // select needed color
NSString *string = ... // the string to colorize
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:string attributes:attrs];
self.scanLabel.attributedText = attrStr;
Run Code Online (Sandbox Code Playgroud)

  • 在那种情况下,我会用NSAttributedString解决这个问题,之后,我会为OP的特定情况指出更简单,更有效的解决方案.遇到这个问题的人可能会对你的解决方案感到沮丧,因为他们正在寻找改变NSAttributedString上文字颜色的方法(这可以解释你的选票). (20认同)
  • Rubén是对的:我来到这里是因为我需要在属性字符串中设置颜色,因为我正在构建一个具有多种颜色和字体大小的复合属性字符串.我需要的关键信息是`NSForegroundColorAttributeName`键,我很难在Apple文档中找到它. (13认同)
  • 我不明白所有的投票.我的答案比使用属性字符串简单得多.OP不需要使用`NSAttributedString`来执行此任务.如果标签的文本需要多个属性,但它没有,那将是一回事.整个标签一次需要一种颜色. (4认同)
  • 谢谢你仍然回答这个问题!! 即使OP实际上并不需要它.很多次我谷歌的东西,最终在堆栈溢出问题,这正是我正在寻找的,只是发现回答问题的智者决定OP实际上并不需要问题标题所要求的和回答了一个完全不同的问题 那么,未来的人们来自搜索结果,其中可能有1000个而不是1个OP,实际上可能想要解决帖子标题中提出的问题.</咆哮> (4认同)

Ano*_*dya 112

使用这样的东西(未编译器检查)

NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSRange range=[self.myLabel.text rangeOfString:texts[sliderValue]]; //myLabel is the outlet from where you will get the text, it can be same or different

NSArray *colors=@[[UIColor redColor],
                  [UIColor redColor],
                  [UIColor yellowColor],
                  [UIColor greenColor]
                 ];

[string addAttribute:NSForegroundColorAttributeName 
               value:colors[sliderValue] 
               range:range];           

[self.scanLabel setAttributedText:texts[sliderValue]];
Run Code Online (Sandbox Code Playgroud)


App*_*Guy 40

Swift 4中:

// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed colour
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
// Set the label
label.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)

Swift 3中:

// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed color
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
// Set the label
label.attributedText = attributedString 
Run Code Online (Sandbox Code Playgroud)

请享用.

  • 没关系,有人心情不好) (2认同)

pab*_*ros 23

对于Swift 4:

var attributes = [NSAttributedStringKey: AnyObject]()
attributes[.foregroundColor] = UIColor.red

let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)

label.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)

对于Swift 3:

var attributes = [String: AnyObject]()
attributes[NSForegroundColorAttributeName] = UIColor.red

let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)

label.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)


Lal*_*hna 6

你可以创建 NSAttributedString

NSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor redColor] };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"My Color String" attributes:attrs];
Run Code Online (Sandbox Code Playgroud)

或者NSMutableAttributedString使用范围应用自定义属性.

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", methodPrefix, method] attributes: @{ NSFontAttributeName : FONT_MYRIADPRO(48) }];
[attributedString addAttribute:NSFontAttributeName value:FONT_MYRIADPRO_SEMIBOLD(48) range:NSMakeRange(methodPrefix.length, method.length)];
Run Code Online (Sandbox Code Playgroud)

可用属性:NSAttributedStringKey


Ima*_*tit 5

在 Swift 4 中,NSAttributedStringKey有一个名为foregroundColor. foregroundColor有以下声明:

static let foregroundColor: NSAttributedStringKey
Run Code Online (Sandbox Code Playgroud)

该属性的值是一个UIColor对象。使用此属性指定渲染期间文本的颜色。如果未指定此属性,则文本呈现为黑色。

以下 Playground 代码显示了如何使用 设置NSAttributedString实例的文本颜色foregroundColor

import UIKit

let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
Run Code Online (Sandbox Code Playgroud)

下面的代码显示了一个可能的UIViewController实现,它依赖于从 aNSAttributedString更新 a 的文本和文本颜色:UILabelUISlider

import UIKit

enum Status: Int {
    case veryBad = 0, bad, okay, good, veryGood

    var display: (text: String, color: UIColor) {
        switch self {
        case .veryBad:  return ("Very bad", .red)
        case .bad:      return ("Bad", .orange)
        case .okay:     return ("Okay", .yellow)
        case .good:     return ("Good", .green)
        case .veryGood: return ("Very good", .blue)
        }
    }

    static let minimumValue = Status.veryBad.rawValue
    static let maximumValue = Status.veryGood.rawValue
}
Run Code Online (Sandbox Code Playgroud)
final class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var slider: UISlider!
    var currentStatus: Status = Status.veryBad {
        didSet {
            // currentStatus is our model. Observe its changes to update our display
            updateDisplay()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Prepare slider
        slider.minimumValue = Float(Status.minimumValue)
        slider.maximumValue = Float(Status.maximumValue)

        // Set display
        updateDisplay()
    }

    func updateDisplay() {
        let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
        let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
        label.attributedText = attributedString
        slider.value = Float(currentStatus.rawValue)
    }

    @IBAction func updateCurrentStatus(_ sender: UISlider) {
        let value = Int(sender.value.rounded())
        guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
        currentStatus = status
    }

}
Run Code Online (Sandbox Code Playgroud)

但是请注意,NSAttributedString对于这样的示例,您实际上并不需要使用它,而可以简单地依赖UILabel'stexttextColor属性。因此,您可以updateDisplay()使用以下代码替换您的实现:

func updateDisplay() {
    label.text = currentStatus.display.text
    label.textColor = currentStatus.display.color
    slider.value = Float(currentStatus.rawValue)
}
Run Code Online (Sandbox Code Playgroud)


Mit*_*gam 5

Swift 5.2 更新

var attributes = [NSAttributedString.Key: AnyObject]()

attributes[.foregroundColor] = UIColor.blue

let attributedString = NSAttributedString(string: "Very Bad",
attributes: attributes)

label.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)