问题
How do you limit the number of characters in a UITextField to 10, and if the user enters more than 10, only record the first 10 characters?
回答1:
This solution deals with a user pasting text or tapping delete key too.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let length = count(textField.text.utf16) + count(string.utf16) - range.length
return length <= 10
}
回答2:
You can check the text before it gets displayed by implementing the UITextFieldDelegate.
class ViewController: UIViewController, UITextFieldDelegate {
textField(textField: UITextField!,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String!) -> Bool {
var shouldChange = false
if countElements(textField.text) < 10 {
shouldChange = true
}
return shouldChange
}
}
来源:https://stackoverflow.com/questions/24641982/how-to-you-set-the-maximum-number-of-characters-that-can-be-entered-into-a-uitex