简体   繁体   English

如何获取在UITextView中键入的最后n个字符?

[英]How do I get the last n characters typed in a UITextView?

Say I want to check if the last 5 characters typed in a UITextView are "mouse". 假设我要检查在UITextView中键入的最后5个字符是否为“鼠标”。 How would I go about doing this? 我将如何去做呢? Specifically in Swift because of how strings indexes are different from Objective-C due to how emojis and the like are stored. 特别是在Swift中,由于表情符号等的存储方式,字符串索引与Objective-C的差异很大。

I cannot seem to figure this out. 我似乎无法弄清楚。 And keep in mind the last n characters may not be typed at the end of the text view, the cursor could be in the middle of the text. 并请记住,最后n个字符可能未在文本视图的末尾键入,光标可能在文本的中间。

您可以使用substringFromIndextextView.text 。因此最后5个字符可以通过该代码来获得。

let strLast5: String =  textView.text.substringToIndex(countElements(textView.text) - 5);

This function will return the last n characters from the last cursor position in the textView, unless the cursor position is too close to the start of the string, in which case it will return from the start of the string to the cursor. 该函数将从textView中的最后一个光标位置返回最后n个字符,除非光标位置离字符串的开头太近,在这种情况下,它将从字符串的开头返回到光标。

To check on each change make the ViewController a delegate of UITextViewDelegate and implement textViewDidChange() 要检查每个更改,请使ViewController成为UITextViewDelegate的委托,并实现textViewDidChange()

class ViewController: UIViewController, UITextViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        textView.delegate = self
    }

    func textViewDidChange(textView: UITextView) {
        print(lastNChars(5, textView: textView)!)
    }

    func lastNChars(n: Int, textView: UITextView) -> String? {
        if let selectedRange = textView.selectedTextRange {
            let startPosition: UITextPosition = textView.beginningOfDocument
            let cursorPosition = textView.offsetFromPosition(startPosition, toPosition: selectedRange.start)
            let chars = textView.text as String
            var lastNChars: Int!
            if n > cursorPosition {
                lastNChars = cursorPosition
            } else {
                lastNChars = n
            }
            let startOfIndex = chars.startIndex.advancedBy(cursorPosition - lastNChars)
            let endOfIndex = chars.startIndex.advancedBy(cursorPosition)
            let lastChars = chars.substringWithRange(startOfIndex ..< endOfIndex)
            return lastChars
        }
        return nil
    }
}

很快,您只需使用textView.text.last

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM