I have the following code, in which I pass a string with of the type "Hello|r World|g"
and the following function converts it into attributedString
with "Hello"
Being red
in color and "World"
being green
in color. I used this as I am passing each of the strings in an array. The function only colors the text until it find a special character as shown in the condition during the end and then colors the text.
Code :
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))
}
}
I get the following error :
'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds'
As I have added println
s , |
and r
get printed.
Please help,Thanks in advance.
It's not a duplicate of this question as |
and r
are getting printed.