Search code examples
swiftxcodeuitextviewviewcontrolleriboutlet

Limit the number of Characters for an IBOutlet TextView, Swift


hopefully someone can guide me and help me out here!!

I'm retrieving some characters data from an API and I have stored the value in an IBOutlet type of UITextView named UITextDisplay. All I'm trying to do is display 300 characters from that data or either less, but for some reason isn't letting me.

Thank you in advance!!

I also delegate the UITextField to the ViewController so it should work and my code compile perfectly fine. The

extension ViewController: UITextViewDelegate
{
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
    {
        textView.text = UITextDisplay.text

        let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)

        return newText.count < 300

    }
}

Also.. is there any way to remove from the characters the end of it "+2637 characters"?? enter image description here

Look forward to any resolution! Amaury,


Solution

  • Please have a look of below question

    Set the maximum character length of a UITextField (In my answer you can also see for UITextView)

    Instead of writing duplicate code everywhere, You can create an extension of UITextView or UITextField to set the max length

    Update:

    Comment Explanation:

    First thing, You need to remove the UITextView delegate method from your current view controller. Because extension of UITextView is internally used UITextViewDelegate

    Note: Delegate is one to one communication. In your case, if you implement delegate in the current view controller then an extension of UITextView is not worked.