XiOS XiOS - 3 months ago 16
Objective-C Question

Track text change in UITextview when not entered through keyboard

I have a UITextView in which character entry is restricted to 100 numbers. I am able to track the character entry using textView:shouldChangeTextInRange:replacementText: method when the text is entered to text view via keyboard.
In my case there is also chance that user just input the characters to text view on button clicks without any interruption of keyboard. In such case the above delegate method does not get called and so I am not able to track the number of characters in the text view and thus allowing more than 100 characters.
How such case should be handled? Please help.


You can try below Swift 3 code:-

@IBAction func buttonClicked(sender: AnyObject) {
          self.textView.text = self.textView.text + "AA" //suppose you are trying to append "AA" on button click which would call the below delegate automatically

//Below delegate of UITextViewDelegate will be called from keyboard as well as in button click
func textViewDidChangeSelection(_ textView: UITextView) {
        if textView.text.characters.count > 100 {

            let tempStr = textView.text
            let index = tempStr?.index((tempStr?.endIndex)!, offsetBy: 100 - (tempStr?.characters.count)!)
            textView.text = tempStr?.substring(to: index!)