用 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];
}

我希望“非常坏”是红色的,“坏”是橙色的,“好”是黄色的,“好”和“非常好”是绿色的。

我不知道如何使用 NSAttributedString来完成这项工作。

204598 次浏览

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

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]];

不需要使用 NSAttributedString。所有您需要的是一个简单的标签与适当的 textColor。此外,这个简单的解决方案将适用于所有版本的 iOS,而不仅仅是 iOS6。

但是,如果您不必要地希望使用 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;

斯威夫特4/5:

// 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

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

好好享受吧。

对于 迅捷5:

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


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


label.attributedText = attributedString

对于 迅捷4:

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


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


label.attributedText = attributedString

对于 斯威夫特3:

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


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


label.attributedText = attributedString

对于 Swift 4,NSAttributedStringKey有一个名为 foregroundColor的静态属性:

static let foregroundColor: NSAttributedStringKey

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

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

import UIKit


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

下面的代码显示了一个可能的 UIViewController实现,该实现依赖于 NSAttributedString,以便从 UISlider更新 UILabel的文本和文本颜色:

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
}
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
}


}

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

func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}

您可以创建 NSAttributedString

NSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor redColor] };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"My Color String" attributes:attrs];

NSMutableAttributedString以使用 Range 应用自定义属性。

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)];

可用属性: NSAttributedStringKey


更新:

Swift 5.1

let message: String = greeting + someMessage
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2.0
    

// Note: UIFont(appFontFamily:ofSize:) is extended init.
let regularAttributes: [NSAttributedString.Key : Any] = [.font : UIFont(appFontFamily: .regular, ofSize: 15)!, .paragraphStyle : paragraphStyle]
let boldAttributes = [NSAttributedString.Key.font : UIFont(appFontFamily: .semiBold, ofSize: 15)!]


let mutableString = NSMutableAttributedString(string: message, attributes: regularAttributes)
mutableString.addAttributes(boldAttributes, range: NSMakeRange(0, greeting.count))

Swift 5.2的更新

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


attributes[.foregroundColor] = UIColor.blue


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


label.attributedText = attributedString

斯威夫特的一句话:

NSAttributedString(string: "Red Text", attributes: [.foregroundColor: UIColor.red])

我喜欢让事情变得简单,试试这个

-(NSArray *) reArrangeArrays:(NSArray *)iObjects {
    

NSMutableArray *Words = [[NSMutableArray alloc] init];
NSMutableArray *Colors = [[NSMutableArray alloc] init];
    

CFIndex OneThree = 0;
CFIndex TwoFour = 1;
for (CFIndex iCounter = 0; iCounter < iObjects.count; iCounter ++) {
        

[Words addObject:[iObjects objectAtIndex:OneThree]];
[Colors addObject:[iObjects objectAtIndex:TwoFour]];
        

OneThree = OneThree + 2;
TwoFour = TwoFour + 2;
        

if (OneThree > iObjects.count || TwoFour > iObjects.count)
break;
}
    

return @[[NSArray arrayWithArray:Words],[NSArray arrayWithArray:Colors]];
}


+(NSMutableAttributedString *) OriginalText:(NSString *)OriginalText WordsAndColors:(NSArray *)WordsAndColors TheRestOfTheTextColor:(UIColor *)TheRestColor {
    

NSArray *Text = [[self.alloc reArrangeArrays:WordsAndColors] objectAtIndex:0];
NSArray *Color = [[self.alloc reArrangeArrays:WordsAndColors] objectAtIndex:1];


NSMutableAttributedString *MutableAttString = [[NSMutableAttributedString alloc] initWithString:OriginalText attributes:@{NSForegroundColorAttributeName : TheRestColor}];


NSString *text = OriginalText;


if (OriginalText != nil) {


for (NSUInteger Counter = 0; Counter < Color.count; Counter ++) {


NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"(%@)",[Text objectAtIndex:Counter]] options:kNilOptions error:nil];


NSRange range = NSMakeRange(0 ,text.length);


[regex enumerateMatchesInString:text options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {


NSRange subStringRange = [result rangeAtIndex:0];


[MutableAttString addAttribute:NSForegroundColorAttributeName value:[Color objectAtIndex:Counter] range:subStringRange];


}];




}
}
return MutableAttString;
}


这是如何使用


NSString *Text = @"Made by @CrazyMind90";
        

NSMutableAttributedString *AttriString = [ViewController OriginalText:Text
WordsAndColors:@[
                

@"Made",UIColor.redColor,
@"by",UIColor.yellowColor,
@"@CrazyMind90",UIColor.blueColor,
            

]
            

TheRestOfTheTextColor:UIColor.whiteColor];
        

    

//Not TextView.text BUT TextView.attributedText
TextView.attributedText = AttriString;


结果

..