1 遵守UITextFieldDelegate代理,并设置代理
self.textField.delegate = self
2 实现以下这个方法
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let string = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString:string)
if (self.textField == textField) {
if string.characters.count > 10 {
textField.text = (string as NSString).substringToIndex(11)
return false
}
}
return true
}