![](/img/trans.png)
[英]How to Test Character Input to UITextField as the User Enters Characters and Prevent Invalid Characters
[英]How to prevent user not to remove particular character in UITextField?
在我的 iPhone 應用程序中,我希望 UITextField 默認為手機號碼具有“+”符號。如果用戶想更改手機號碼,那么他/她可以。 但是他們不允許從 UITextField 中刪除“+”。 “+”符號始終保持在 UITextField 中。
例如:-
+911234567890 - 正確的號碼
911234567890 - 號碼錯誤。 + 是必需的。
我嘗試使用 UITextField 委托方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
並且還使用了通知“ UIControlEventEditingChanged ”。
提前致謝。
試試這個。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *head= [textField.text substringToIndex:range.location];
NSString *tail= [textField.text substringFromIndex:range.location];
NSString *phoneNumber = [NSString stringWithFormat:@"%@%@%@",head,string,tail];
if ([string isEqualToString:@""]) {
NSString *deleteString = [tail substringToIndex:1];
if ([deleteString isEqualToString:@"+"]) {
return NO;
}
}else if(![self isValidPhoneNumber:phoneNumber]){
return NO;
}
return YES;
}
通過正則表達式檢查有效的電話號碼
-(BOOL)isValidPhoneNumber:(NSString*)phoneNumber{
NSString *phoneNumberPattern = @"[+]([0-9])*";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneNumberPattern];
BOOL match = [predicate evaluateWithObject:phoneNumber];
if (match) {
NSLog(@"VALID");
return YES;
}else{
NSLog(@"INVALID");
}
return NO;
}
防止在第一個字符之前添加任何字符而不是第一個字符:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
return range.location == 0 && (range.length == 0 || range.length == 1) ? NO : YES;
}
嘗試這個。 在這里,我對 UITextField 使用左填充。 txtf是我的 UITextField。
UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(5, 0, 15, 30)];
lbl.textAlignment=NSTextAlignmentCenter;
[lbl setText:@"+"];
_txtf.leftView=lbl;
[_txtf setLeftViewMode:UITextFieldViewModeAlways];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.