假设我想检查 UITextView
中输入的最后 5 个字符是否为“鼠标”。我该怎么做呢?特别是在 Swift 中,因为字符串索引与 Objective-C 不同,因为表情符号等的存储方式不同。
我似乎无法弄清楚这一点。请记住,最后 n 个字符可能不会在 TextView 的末尾键入,光标可能位于文本的中间。
最佳答案
该函数将从textView中最后一个光标位置返回最后n个字符,除非光标位置太接近字符串的开头,在这种情况下它将从字符串的开头返回到光标。
要检查每个更改,请使 ViewController 成为 UITextViewDelegate 的委托(delegate) 并实现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
}
}
关于ios - 如何获取 UITextView 中输入的最后 n 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129527/