Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current paragraph in UITextView?

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
            }
        }

    }

}
like image 934
Elida Avatar asked Feb 27 '16 00:02

Elida


1 Answers

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))
like image 68
Nate Cook Avatar answered Sep 22 '22 19:09

Nate Cook