最近項目接近尾聲, 將項目中遇到的問題, 分享一下.
具體要求電話號碼3位, 7位, 11位中間加入分隔符"-"
//控制textfield輸入長度
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == self.newtextfield || textField == self.agenntextfield) {
//這里的if時候為了獲取刪除操作,如果沒有次if會造成當達到字數(shù)限制后刪除鍵也不能使用的后果.
if (range.length == 1 && string.length == 0) {
return YES;
}else if (textField.text.length == 11) {
textField.text = [textField.text substringToIndex:11];
[textField resignFirstResponder];
return NO;
}
}
return YES;
}
//當textfield成為第一響應(yīng)者的時候
- (void)textFieldDidBeginEditing:(UITextField *)textField{
if ((textField.tag == 1)) {
NSMutableString * str = [[NSMutableString alloc] initWithString:self.newtextfield.text];
for (int a = 0; a < str.length; a++) {
unichar c = [str characterAtIndex:a];
NSRange range = NSMakeRange(a, 1);
if (c == '-'){ //此處可以是任何字符
[str deleteCharactersInRange:range];
--a;
}
}
self.newtextfield.text = str;
} else if (textField.tag == 2){
NSMutableString * str = [[NSMutableString alloc ] initWithString:self.agenntextfield.text];
for (int a = 0; a < str.length; a++) {
unichar c = [str characterAtIndex:a];
NSRange range = NSMakeRange(a, 1);
if (c == '-'){ //此處可以是任何字符
[str deleteCharactersInRange:range];
--a;
}
}
self.agenntextfield.text = str;
}
}
//當textfield失去第一響應(yīng)者的時候觸發(fā)
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if (textField.tag == 1) {
NSMutableString * str = [[NSMutableString alloc] initWithString:self.newtextfield.text];
[textField resignFirstResponder];
for (int a = 0; a < str.length; a++) {//加入@"-"
if (a == 3) {
[str insertString:@"-" atIndex:a];
} else if (a == 8){
[str insertString:@"-" atIndex:a];
}
}
self.newtextfield.text = str;
} else if (textField.tag == 2){
NSMutableString * str = [[NSMutableString alloc] initWithString:self.agenntextfield.text];
[textField resignFirstResponder];
for (int a = 0; a < str.length; a++) {//加入@"-"
if (a == 3) {
[str insertString:@"-" atIndex:a];
} else if (a == 8){
[str insertString:@"-" atIndex:a];
}
}
self.agenntextfield.text = str;
}
return YES;
}