ios - 如何快速更改字符串中所有数字的颜色

标签 ios swift

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

var mystring = "abc 3423 opqrs 474598 lmno 343543"

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

输出:

abc 3423 opqrs 474598 lmno 343543

-----in red----------in red-----------in red---

最佳答案

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

}

这是截图

enter image description here

关于ios - 如何快速更改字符串中所有数字的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37518588/

相关文章:

swift - 如何从 CLLocationManager 传递经度和纬度以使用全局 swift

Swift 无法在 Xcode 8 上通过 cocoapods 导入 SwiftyJSON 和 Alamofire

ios - iOS 12 应用程序扩展可以写入 Healthkit

ios - 中断 UIView 转换

ios - 无法在 xcode 6.1 中调用 != nil 生成错误

ios - 是否可以在 xcode 中创建新的一行选项卡?

ios - 如何让 iOS 键盘在整个应用程序生命周期中出现/保持?

ios - 使用 AutoLayout 在方向更改时更改 UITextView 高度

swift - 接受泛型参数的函数

swift - 将 CGPathAddArcToPoint 转换为 Swift 3