我有下面的代碼,其中,我傳遞字符串與類型"Hello|r World|g"
的和下面的函數將其與"Hello"
作爲在彩色red
和"World"
被轉換爲attributedString
顏色爲。我使用這個,因爲我傳遞數組中的每個字符串。該功能只會對文本進行着色,直到它找到特殊字符(如最終條件中所示),然後爲文本着色。錯誤「NSMutableRLEArray objectAtIndex:effectiveRange ::出界」
代碼:
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
小號,|
和r
已打印。 請幫忙,提前致謝。
它不是this question的副本,因爲|
和r
正在打印。
可能重複[NSMutableAttributedStrings - objectAtIndex:effectiveRange ::出界(http://stackoverflow.com/questions/11571948/nsmutableattributedstrings-objectatindexeffectiverange-out-of-bounds) –
你是變異的串隨着你走,改變它的長度,所以你需要在你做替換之後調用'stringByReplacingOccurrencesOfString' – Paulw11
i - 2來減少i。除了for循環最後開始使用超出字符串末尾的索引,因爲您只需縮短它就可以了。 –