ios - 更改 UIlabel 中的某些字符
问题描述
所以我有一个 UILabel ->
mylabel = "ios is cool"
(初始颜色为红色)
现在我想将文本“ios”的颜色更改为蓝色,剩余的文本应该只有红色。
我将如何实现这一目标
解决方案
设置你的 UILabel 文本
let text = textColorChange(fullText: "ios is cool", changeColorText: "ios")
mylabel.attributedText = text
在你的 UIViewController 中写这个函数
func textColorChange(fullText: String, changeColorText: String) -> NSMutableAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: changeColorText)
let pattern = fullText.lowercased
let range: NSRange = NSMakeRange(0, changeColorText.count)
let regex = try! NSRegularExpression(pattern: pattern(), options: NSRegularExpression.Options())
regex.enumerateMatches(in: changeColorText.lowercased(), options: NSRegularExpression.MatchingOptions(), range: range) { (textCheckingResult, matchingFlags, stop) -> Void in
let subRange = textCheckingResult?.range
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: subRange!)
}
return attributedString
}
推荐阅读
- python-3.x - 尝试获取二叉树中的最后一个节点
- python - 如何在python中将日期转换为文本?
- java - 我的操作栏显示为没有按钮的空白矩形。为什么?
- c++ - 有没有办法用递归函数的参数包部分专门化模板?
- excel - 如何将列表框引用到特定工作表?
- swift - 将一个空对象数组模型传递给另一个视图控制器 Swift
- python - 将 url 模式转换为 Django 1.11
- java - 反射 Class.getDeclaredFields() 没有在 Android 上检索任何内容
- swift - 摄氏的快速测量格式化程序不起作用
- javascript - javascript中使用拼接的袜子商人问题不起作用