在swift中为所有出现的字符串着色 [英] Color all occurrences of string in swift

查看:81
本文介绍了在swift中为所有出现的字符串着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码

var textSearch="hi"
var textToShow="hi hihi hi" 
var rangeToColor = (textToShow as NSString).rangeOfString(textSearch)
var attributedString = NSMutableAttributedString(string:textToShow)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor() , range: rangeToColor)
TextView.attributedText=attributedString

给我NSRange为TextView中的字符串着色。
问题是我只返回第一次出现。
如果单词包含hi hihi hi,则只有第一个hi是彩色的。
如何才能获得所有字符串?

gives me NSRange to color a string inside the TextView. The problem is that I only returns the first occurrence. If the word contains "hi hihi hi" only the first "hi" is colored. How can I get all occurrences of the string?

推荐答案

Swift 3

let attrStr = NSMutableAttributedString(string: "hi hihi hey")
let inputLength = attrStr.string.characters.count
let searchString = "hi"
let searchLength = searchString.characters.count
var range = NSRange(location: 0, length: attrStr.length)

while (range.location != NSNotFound) {
    range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
    if (range.location != NSNotFound) {
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellow(), range: NSRange(location: range.location, length: searchLength))
        range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
    }
}

Swift 2

let attrStr = NSMutableAttributedString(string: "hi hihi hey")
let inputLength = attrStr.string.characters.count
let searchString = "hi"
let searchLength = searchString.characters.count
var range = NSRange(location: 0, length: attrStr.length)

while (range.location != NSNotFound) {
    range = (attrStr.string as NSString).rangeOfString(searchString, options: [], range: range)
    if (range.location != NSNotFound) {
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: NSRange(location: range.location, length: searchLength))
        range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
    }
}

这篇关于在swift中为所有出现的字符串着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆