Set the maximum character length of a UITextField

前端 未结 30 2245
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 02:45

    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.

提交回复
热议问题