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.
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!