我有一个UITextView,并且正在使用它的标记器来检查用户点击的单词。
我的目标是改变标记器所认为的单词。目前,它似乎将单词定义为连续字母数字字符,我希望将一个单词定义为不是空格字符(“")的连续字符。
例如:'foo-bar‘、'foo/bar’和'foo@@bar‘目前都将被视为两个单独的单词('foo’和'bar'),但我希望它们都被视为一个单词(因为它们中没有一个包含空格)。
文档讨论了对UITextInputStringTokenizer类进行子类化的问题,但是我找不到一个这样做的人的例子,我也不知道如何实现所需的方法:
func isPosition(position: UITextPosition, atBoundary granularity: UITextGranularity, inDirection direction: UITextDirection) -> Bool
func isPosition(position: UITextPosition, withinTextUnit granularity: UITextGranularity, inDirection direction: UITextDirection) -> Bool
func positionFromPosition(position: UITextPosition, toBoundary granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextPosition?
func rangeEnclosingPosition(position: UITextPosition, withGranularity granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextRange?发布于 2022-09-14 11:47:23
总之,创建扩展UITextInputStringTokenizer的实现,使大多数方法保持不变(或者只调用super)。
当粒度是word时,您只需要重写isPosition(_:atBoundary:inDirection:)和isPosition(_:withinTextUnit:inDirection:),以检查该位置旁边的字符是否位于单词边界,即字母数字字符和空格一起。默认实现还将返回其他非空格的true,这些非空格被认为不是单词的一部分,相反,您可以将它们视为单词的一部分。当粒度不是word时,您也可以默认为super。
发布于 2022-12-03 19:23:03
//创建UITextInputStringTokenizer类CustomTokenizer的子类: UITextInputStringTokenizer {
// Override the rangeEnclosingPosition method so that it looks for characters that are not a space (" ")
override func rangeEnclosingPosition(position: UITextPosition, withGranularity granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextRange? {
// First check if the range enclosing the position is not nil
guard let range = super.rangeEnclosingPosition(position: position, withGranularity: granularity, inDirection: direction) else {
return nil
}
// Then define a string of characters that are not a space (" ")
let nonSpaceCharacterSet = CharacterSet.init(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890_")
// Then define a range which will be used to search for the non space characters
let startIndex = range.start
let endIndex = range.end
let searchRange = startIndex..<endIndex
// Then define a string based on the range
let text = self.textInput.text(in: searchRange)
// Then search the string for any characters that are not a space (" ")
if let _ = text?.rangeOfCharacter(from: nonSpaceCharacterSet) {
// If any characters that are not a space (" ") are found, then return the range
return range
} else {
// Otherwise, return nil
return nil
}
}}
//然后将UITextView的令牌程序设置为CustomTokenizer textView.tokenizer = CustomTokenizer(textInput: textView)
https://stackoverflow.com/questions/29434960
复制相似问题