Get current paragraph in UITextView?

女生的网名这么多〃 提交于 2019-12-12 21:13:32

问题


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:


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


来源:https://stackoverflow.com/questions/35664039/get-current-paragraph-in-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!