Highlight Arabic Text with Timer

2019-08-04 06:16发布

I'm trying to highlight the arabic text but it is not working,at last the program crashed with error:

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

my code is :

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()

}

and highlight part is:

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

    }

This code is working but their index range miss matched at last...

2条回答
虎瘦雄心在
2楼-- · 2019-08-04 06:41

It looks like wordNum keep increasing and increasing without bound. If you never stop the timer or reset wordNum, this is clearly going to run off the end of the array eventually.

You likely need to store the timer in a property and invalidate it whenever you get to the end of your word list.

查看更多
唯我独甜
3楼-- · 2019-08-04 06:46

Delete the timer.fire(), the timer is already scheduled when you create it. Also, try to delete the timer parameter in the keepHighlighting function and set the userInfo to nil and call the label from the userInfo directly.

查看更多
登录 后发表回答