使用计时器突出显示阿拉伯文本



我正在尝试突出显示阿拉伯语文本,但它不起作用,最后程序崩溃并显示错误:

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds'

我的代码是:

super.viewDidLoad()
myMutableString = NSMutableAttributedString(string: longString)
var currentLocation = 0
var currentLength = 0
var char = CharacterSet.whitespaces
let arrayOfWords = longString.components(separatedBy: char)
for word in arrayOfWords
{
    currentLength = word.characters.count
    ranges.append(NSRange(location: currentLocation, length: currentLocation+currentLength))
    currentLocation += currentLength + 1
}

let mySelector = #selector(self.keepHighlighting)
let timer = Timer.scheduledTimer(timeInterval:0.5, target: self, selector: mySelector, userInfo: tempLbl , repeats: true)
timer.fire()
}

突出显示部分是:

func keepHighlighting(timer:Timer)
    {
        let lbl = timer.userInfo as! UILabel
        myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Al_Mushaf", size: 40.0)!, range:ranges[wordNum])
        myMutableString.addAttribute(NSForegroundColorAttributeName,value: UIColor.blue,range: ranges[wordNum] )

        lbl.attributedText = myMutableString
        wordNum = wordNum + 1
    }

这段代码正在工作,但它们的索引范围最终不匹配......

看起来wordNum不断增加,没有限制。如果您从不停止计时器或重置 wordNum,这显然最终会从数组的末尾运行。

您可能需要将计时器存储在属性中,并在到达单词列表末尾时invalidate计时器。

删除timer.fire() ,创建计时器时已安排计时器。另外,尝试删除 keepHighlighting 函数中的 timer 参数,并将userInfo设置为 nil,并直接从userInfo调用标签。

最新更新