5

I want to detect the current paragraph, this is my code so far, but it doesn't work so well. Lets say I have 3 paragraphs and when the cursor is between them, it selects the next one, which is not right. Is there a better way to do this?

With this code, I want to detect the current paragraph, then change the font of that paragraph, and then continue writing with that font.

func textViewDidChangeSelection(textView: UITextView)
{

   // print("selected")
    //stylesDefaults()
    var arr = [String]()

    composeTextView.text.enumerateSubstringsInRange(Range(start: composeTextView.text.startIndex, end: composeTextView.text.endIndex), options: NSStringEnumerationOptions.ByParagraphs,
        { (substring, substringRange, enclosingRange, bool) -> () in arr.append(substring!)
    })

    if(composeTextView.text.characters.count != 0)
    {
        self.titleTextField.text = arr[0]
    }

    let currentRange : NSRange = composeTextView.selectedRange
    var charCounter : Int = 0
    var found : Bool = false
    for (var i = 0; i < arr.count; i++)
    {
        charCounter = charCounter + arr[i].characters.count
        if found == false
        {
            if(charCounter > currentRange.location)
            {
                print(arr[i])
                found = true
            }
        }

    }

}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Elida
  • 117
  • 9

1 Answers1

5

It sounds like you need NSString's paragraphRangeForRange: method:

let composeText = composeTextView.text as NSString
let paragraphRange = composeText.paragraphRangeForRange(composeTextView.selectedRange)
print(composeText.substringWithRange(paragraphRange))
Nate Cook
  • 92,417
  • 32
  • 217
  • 178