使用计时器

时间:2017-04-13 13:20:19

标签: ios objective-c swift3

我试图突出显示阿拉伯语文字,但它无法正常工作,最后该程序崩溃了错误:

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

    }

此代码正常运行,但其索引范围最终未达到匹配...

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

看起来wordNum不断增加和增加。如果你永远不会停止计时器或重置wordNum,这显然会最终在数组末尾运行。

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