I did this in Swift for an 8 character limit when using a number pad.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return !(textField.text?.characters.count == MAX_LENGTH && string != "")
}
I had to test for string != "" to allow the delete button to work on the number pad, otherwise it wouldn't allow deleting characters in the text field after it reached its max.