Get currently typed word in UITextView

前端 未结 3 1122
耶瑟儿~
耶瑟儿~ 2020-12-11 13:25

I\'m trying to make a \"tagging window\" much like the one used in Facebook where you type \"@\" and it make suggestions among your friends on which one to tag. I\'d like th

相关标签:
3条回答
  • 2020-12-11 13:33

    Swift 4:

    This solution worked for me inside the method func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool of UITextViewDelegate.

      func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            guard let textFieldText = textView.text,
                  let rangeOfTextToReplace = Range(range, in: textFieldText) else {
                    return false
            }
    
            let currentText = textFieldText.replacingCharacters(in: rangeOfTextToReplace, with: text)
        
            return count <= 150
        }
    
    0 讨论(0)
  • 2020-12-11 13:39

    This works for me.

    extension UITextView {
    
    var currentWord : String? {
    
        let beginning = beginningOfDocument
    
        if let start = position(from: beginning, offset: selectedRange.location),
            let end = position(from: start, offset: selectedRange.length) {
    
            let textRange = tokenizer.rangeEnclosingPosition(end, with: .word, inDirection: 1)
    
            if let textRange = textRange {
                return text(in: textRange)
            }
        }
        return nil
       }
    }
    
    0 讨论(0)
  • 2020-12-11 13:44

    As usual I spent a fair amount of time trying to get this to work, and minutes after I posted the question I got it working. So here's the code I used, but I have deprecated call for the let myRange

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    
        let myRange = Range<String.Index>(start: textView.text.startIndex, end: textView.text.startIndex.advancedBy(range.location))
        var subString = textView.text.substringWithRange(myRange)
        subString += text
    
        let wordArray = subString.componentsSeparatedByString(" ")
        if let wordTyped = wordArray.last {
            currentWord = wordTyped
            print("word typed: " + wordTyped)
        }
    
        return true
    }
    
    0 讨论(0)
提交回复
热议问题