如何快速更改字符串中所有数字的颜色 [英] How to change colour of all numbers in a string in swift
本文介绍了如何快速更改字符串中所有数字的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更改swift
代码中字符串中存在的所有数字的颜色.示例:
I am trying to change colour for all numbers present in a string in swift
code.Example:
var mystring = "abc 3423 opqrs 474598 lmno 343543"
(将所有数字颜色更改为红色)
(change all number colour to red)
输出:
abc 3423 opqrs 474598 lmno 343543
abc 3423 opqrs 474598 lmno 343543
-----红色------------红色-----------红色---
-----in red----------in red-----------in red---
推荐答案
我对一个项目做了类似的事情,因此基本上检查此数字是否为数字并保存其位置,然后使用NSAttributedString可以轻松更改字符颜色像这样:-
I did something like this for a project, So basically this check whether it's a number and save it's location then by using NSAttributedString, we can easily change the character color like this :-
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
Here is a screenShot
这篇关于如何快速更改字符串中所有数字的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文