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

时间:2016-05-30 06:02:39

标签: ios swift

我正在尝试更改swift代码中字符串中所有数字的颜色。例如:

var mystring = "abc 3423 opqrs 474598 lmno 343543"

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

输出:

  

abc 3423 opqrs 474598 lmno 343543

     

-----红色----------红色-----------红色---

6 个答案:

答案 0 :(得分:4)

我为一个项目做了类似的事情,所以基本上检查它是否是一个数字然后通过使用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

enter image description here

答案 1 :(得分:2)

我认为有一种更有效的方法可以做到这一点。不是找到数字的位置,然后为每个数字创建一个范围,而是动态地改变它。

    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中的成员资格是本地化友好的。

答案 2 :(得分:0)

我对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中使用。

希望这会有所帮助:)

答案 3 :(得分:0)

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

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)

答案 4 :(得分:0)

以下是使用Swift 5的扩展程序,以Zig的答案作为参考:

cfoutput

答案 5 :(得分:-2)

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;