如何在UITextView中输入最后n个字符? [英] How do I get the last n characters typed in a UITextView?

查看:136
本文介绍了如何在UITextView中输入最后n个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想检查 UITextView 中输入的最后5个字符是否为mouse。我该怎么做呢?特别是在Swift中,因为字符串索引与Objective-C的不同,因为存储了表情符号等。

Say I want to check if the last 5 characters typed in a UITextView are "mouse". 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.

我似乎无法弄清楚这一点。请记住,最后n个字符可能不会在文本视图的末尾键入,光标可能位于文本的中间。

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.

推荐答案

此函数将返回textView中最后一个光标位置的最后n个字符,除非光标位置太靠近字符串的开头,在这种情况下,它将从字符串的开头返回到光标。

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.

要检查每个更改,请使ViewController成为UITextViewDelegate $的委托b $ b并实现textViewDidChange()

To check on each change make the ViewController a delegate of UITextViewDelegate and implement 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
    }
}

这篇关于如何在UITextView中输入最后n个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆