0

I 'm trying to add attributes to a certain range of characters in textView on basis of break line character.The app is crashing and throwing out of bound error.Not sure why because the range to which I'm applying attributes is within the text length.

Here's the method to get the range:

    func findParagraphBy(postion:Int)->NSRange{
    var startIndex = 0
    var endIndex = 0
    
           
    for (index,char) in textView.text.enumerated(){
        if index<postion && char == "\n"{
            startIndex = index
        }else if index>=postion && char == "\n"  && endIndex == 0{
            endIndex = index
            
        }else{
            continue
        }
    }
    if endIndex == 0{
        endIndex = self.textView.text.count-1
    }

    let range = NSMakeRange(startIndex, endIndex)
    
    return range
}

Here's the method to apply Attributes

 func applyAttr(){
    let range = findParagraphBy(postion: textView.selectedRange.location-1)     
    self.textView.textStorage.addAttributes(self.currentAttribute.getAttr(), range: range)
    
    
}
NewUser
  • 21
  • 3
  • You are looking for previous and next `\n` of position, and make a range from it, right? There might be an easier way with range(of:options:range:), giving a range from 0 to position, and position to max... Else you might want to debug: print the values of each variable, see if it seems correct to find your issue... For instance, if your String is empty, the `endIndex` will be -1 ? And a NSRange, it's start index - length, not start index - end index... That's the main culprit of your crash I guess... – Larme Nov 28 '21 at 21:26
  • @Larme It worked with range(of:options:range:).Thanks :) – NewUser Nov 29 '21 at 06:17

0 Answers0