swift方法
限制輸入個(gè)數(shù)和只能輸入的內(nèi)容
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var maxNum = 11
if textField == newPhoneNumber {
maxNum = 11
}else if textField == iconCode{
maxNum = 4
}else if textField == smsCode{
maxNum = 6
}
if textField == iconCode {
// 只允許的字符集
let charact = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789").inverted
// 返回一個(gè)數(shù)組,從給定字符串中除去給定字符集的子字符串
let array = string.components(separatedBy: charact)
// 返回一個(gè)新的字符串焦读,通過在序列元素之間加入給定的字符
let filerString = array.joined(separator: "")
return filerString == string
}
// 限制個(gè)數(shù)
let currentText = textField.text ?? ""
guard let stringRange = Range(range, in: currentText) else { return false }
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
return updatedText.count <= maxNum
}
oc方法
限制輸入內(nèi)容
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.XSPaasswordTF || textField == self.XSPasswordAgain) {
NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
return YES;
}
限制個(gè)數(shù)
因?yàn)檫@個(gè)協(xié)議只有在將要變化前執(zhí)行潭苞,不是變化后執(zhí)行,否則打印的值和沒有最新輸入的字符
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSMutableString * XSString = [NSMutableString stringWithString:textField.text];
[XSString replaceCharactersInRange:range withString:string];
if (XSString.length>15) {
textField.text = [XSString substringToIndex:15];
return NO;
}
return YES;
}