0

I want to display the same warning as in the picture when entering over the allowed number of characters. This happens on import without any other action.

enter image description here

Here is my code to limit characters:

 private func textLimit(existingText: String?, newText: String, limit: Int) -> Bool {
        let text = existingText ?? ""
        let isAtLimit = text.count + newText.count <= limit
        return isAtLimit
    }

and delegate:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return self.textLimit(existingText: textField.text, newText: string, limit: 5)
    }

I have found the solution:

   private func textLimit(existingText: String?, newText: String, limit: Int) -> Bool {
        let text = existingText ?? ""
        let limitText = text.count + newText.count
        let isAtLimit = text.count + newText.count <= limit
        if limitText > limit {
            var alert: UIAlertController!
            alert = UIAlertController(title: "", message: "Character limit exceeded", preferredStyle: .alert)
            self.present(alert, animated: true, completion: nil)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                alert.dismiss(animated: true, completion: nil)
            }
        }
        return isAtLimit
    }

But how can I automatically break the trailing characters when pasting a string? And when you put the cursor somewhere to add text, the redundant character will be replaced? Hope everyone understand the question, sorry my english is not good!

solitary
  • 3
  • 2
  • 1
    Your code for limiting characters looks okay; is it? If so, where's the part about the alert? – matt Feb 09 '21 at 02:44
  • See this for an implementation of the text field delegate method - https://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield/1773257#1773257 – Paulw11 Feb 09 '21 at 02:47

1 Answers1

0

This kind of alert seems like a Toast. There's an open source iOS library called Toast-Swift that produces this kind of alert. Install it on your project and then just before the return of the textField:shouldCharactersIn:replacementString: method you can call the component to display an alert:

self.view.makeToast("Character limit exceeded.")

You can check the component docs for more advanced customization of this dialog.