Get current paragraph in UITextView?

2019-07-14 15:30发布

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

    }

}

1条回答
闹够了就滚
2楼-- · 2019-07-14 16:10

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))
查看更多
登录 后发表回答