如何在swift中更改字符串中所有数字的颜色

我试图改变swift代码中字符串中出现的所有数字的颜色。例如:

 var mystring = "abc 3423 opqrs 474598 lmno 343543" 

(将所有数字颜色更改为红色)

输出:

abc 3423 opqrs 474598 lmno 343543

—–红色———-红色———–红色—

我为一个项目做了类似的事情,所以基本上检查它是否是一个数字然后通过使用NSAttributedString保存它的位置,我们可以很容易地改变这样的字符颜色: –

 class ViewController: UIViewController { @IBOutlet weak var mylabel: UILabel! let numbers = ["0","1","2","3","4","5","6","7","8","9"] var mystring = "abc 3423 opqrs 474598 lmno 343543" override func viewDidLoad() { super.viewDidLoad() let myAttributedString = NSMutableAttributedString(string: "\(self.mystring)") var locations: [Int] = [] let characters = mystring.characters var i = 0 for letter in characters { i = i + 1 letter.debugDescription if numbers.contains(String(letter)) { locations.append(i) } } for item in locations { print(item) let myRange = NSRange(location: item - 1, length: 1) myAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: myRange) } self.mylabel.attributedText = myAttributedString // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

这是一个screenShot

在此处输入图像描述

我认为这是一种更有效的方法。 而不是找到数字的位置,然后为每个数字创建一个范围,只需动态更改即​​可。

  let myString = "abc 3423 opqrs 474598 lmno 343543" let redFont = [NSForegroundColorAttributeName: UIColor.red] let myAttributedString = NSMutableAttributedString() for letter in myString.unicodeScalars { let myLetter : NSAttributedString if CharacterSet.decimalDigits.contains(letter) { myLetter = NSAttributedString(string: "\(letter)", attributes: redFont) } else { myLetter = NSAttributedString(string: "\(letter)") } myAttributedString.append(myLetter) } myLabel.attributedText = myAttributedString 

除了更高效之外,如果您打算支持,那么检查CharacterSet.decimalDigits中的成员资格是本地化友好的。

我对swift不是很熟悉,但我已经尝试在目标c中进行演示,如果可以提供帮助,它可以正常工作

  NSString *str = @"abc 3423 opqrs 474598 lmno 343543"; NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc]initWithString:@"abc 3423 opqrs 474598 lmno 343543"]; NSArray *arr = [str componentsSeparatedByString:@" "]; for (int i = 0; i < arr.count; i++) { NSString *temp = [arr objectAtIndex:i]; NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; if ([temp rangeOfCharacterFromSet:notDigits].location == NSNotFound) { NSDictionary *attrs = @{ NSForegroundColorAttributeName:[UIColor redColor] }; NSRange range = [str rangeOfString:[arr objectAtIndex:i]]; [str1 addAttributes:attrs range:range]; } } UILabel *temp = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, 300, 50)]; [self.view addSubview:temp]; temp.attributedText = str1; 

您可以使用逻辑和概念,并可以在swift中使用您的要求。

希望这会有所帮助:)

首先,我们需要找到字符串中存在的数字范围。 一种方法是使用正则表达式

 func findNumberRanges(string: String) -> [NSRange]{ let nsString = string as NSString let regex = try? NSRegularExpression(pattern: "[0-9]+", options: []) let matches = regex?.matches(in: string, options: .withoutAnchoringBounds, range: NSMakeRange(0, nsString.length)) return matches?.map{$0.range} ?? [] } 

然后我们可以迭代数字范围来添加属性,在这种情况下设置红色。

 func attributedNumberString(string: String, numberAttribute: [String: Any]) -> NSAttributedString{ let ranges = findNumberRanges(string: string) let attributedString = NSMutableAttributedString(string: string) for range in ranges{ attributedString.addAttributes(numberAttribute, range: range) } return attributedString } 

以下是它的使用方法:

 let redColorAttribute = [ NSForegroundColorAttributeName: UIColor.red] attributedNumberString(string: "6h40m", numberAttribute: redColorAttribute) 
 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:"Your Text"]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)]; //give range where you want [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];//give range where you want [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)]; //give range where you want YourLable.attributedText = string;