Remove the extra pasted text textview swift || UITextview character count when copy paste iOS swift || substring for limiting characters swift

SOLUTION:

Use the textview delegate method to control the user input within your Limit.
Inside the below delegate method do the process.It will control the text entry in all scenarios like user typing text or copy pasted text.

    func textView(_ textView: UITextView,
                  shouldChangeTextIn range: NSRange,

                  replacementText text: String) -> Bool{
//this part is used for get the user inputstring and also the previously entered string
        var nsString:NSString = ""
        
        if textView.text != nil  && text != "" {
            nsString = textView.text! as NSString
            nsString = nsString.replacingCharacters(in: range, with: text) as NSString
        }   else if (text == "") && textView.text != ""  {
            nsString = textView.text! as NSString
            nsString = nsString.replacingCharacters(in: range, with: text) as NSString
            
        } else if (text == "") && textView.text == "" {
            textView.text = ""
        }

        guard let texts = textView.text else { return true }
        let currentText = nsString as NSString
        if currentText.length >= 10 {
        textView.text = currentText.substring(to: 10)
        }
        return currentText.length <= 10

}

The above example will give the user to enter only 10 characters inside the textview as well as in copy paste also.

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift