我有下面的代码,在其中我传递了一个类型为的字符串,下面"Hello|r World|g"
的函数将它转换为attributedString
颜色"Hello"
和red
颜色。我在传递数组中的每个字符串时使用了它。该函数仅对文本着色,直到它在结束期间找到条件所示的特殊字符,然后对文本着色。"World"
green
代码 :
func formatAttributedString(string:String)->NSMutableAttributedString {
var strCopy=string as NSString
var color:UIColor=UIColor()
var attributedString:NSMutableAttributedString!
for var i:Int=0;i<strCopy.length-2;i++ {
if (string[i] == "|") {
println("|")
var j:Int
if string[i+1] == "r" {
color=UIColor(red: 249, green: 39, blue: 14, alpha: 1)
strCopy = strCopy.stringByReplacingOccurrencesOfString("|r", withString: "", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, i + 2))
println("r")
}
else if string[i+1] == "v" {
color=UIColor(red: 161, green: 153, blue: 249, alpha: 1)
strCopy = strCopy.stringByReplacingOccurrencesOfString("|v", withString: "", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, i + 2))
println("v")
}
else if string[i+1] == "y" {
color=UIColor(red: 235, green: 223, blue: 145, alpha: 1)
strCopy = strCopy.stringByReplacingOccurrencesOfString("|y", withString: "", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, i + 2))
println("y")
}
else if string[i+1] == "g" {
color=UIColor(red: 174, green: 227, blue: 79, alpha: 1)
strCopy = strCopy.stringByReplacingOccurrencesOfString("|y", withString: "", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, i + 2))
println("g")
}
else if string[i+1] == "b" {
color=UIColor(red: 107, green: 224, blue: 240, alpha: 1)
strCopy = strCopy.stringByReplacingOccurrencesOfString("|b", withString: "", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, i + 2))
println("b")
}
for j=i; j>=0;j-- {
if string[j] == " " || string[j] == "/" || string[j] == "." || string[j] == "\"" || string[j] == "\n" || string[j] == "<" || string[j] == "\t" || string[j] == "("{
println("/")
break
}
}
attributedString=NSMutableAttributedString(string: strCopy)
attributedString.addAttribute("NSForegroundColorAttributeName", value: color, range: NSMakeRange(j, i-j))
}
}
我收到以下错误:
'NSMutableRLEArray objectAtIndex:effectiveRange:: 越界'
正如我添加了println
s ,|
并r
得到打印。请帮助,在此先感谢。
它不是这个问题的重复,因为|
它r
正在被打印出来。