2010-07-02 5 views
2

UIView를 만들고 싶습니다. 사용자가 편집을 마쳤을 때 여러 UITextFields가 각각의 유효성을 검사합니다. 뷰 컨트롤러는 각 UITextField에 대한 대리자입니다. 사용자가 해당 UITextField 중 하나의 값을 변경하고 키보드의 "완료"를 터치하거나보기의 다른 텍스트 필드를 터치하면 변경 내용을 저장하고 유효성을 검사합니다. 여기서 아이디어는 사용자에게 즉각적인 피드백을 제공하고 유효하지 않은 속성 값이 입력되면 더 이상 진행하지 못하게하는 것입니다. 입력 문자열의 유효성을 확인하는여러 UITextFields 유효성 검사

가장 위임 방법 textFieldShouldEndEditing됩니다 : 텍스트 필드와 textViewShouldEndEditing에 대한

나는 textFieldShouldEndEditing:에 저장/유효성 검사 논리를 넣을 것을 제안 애플의 지원 문서,에 Text and Web Programming Guide 읽고 : 텍스트보기 용. 이 메소드는 텍스트 필드 또는 텍스트보기가 첫 번째 응답자 상태를 종료하기 직전에 호출됩니다. NO를 반환하면 그 일이 일어나지 않으며 결과적으로 텍스트 개체는 편집의 초점으로 유지됩니다. 입력 된 문자열이 유효하지 않은 경우 사용자에게 오류를 알리는 경고를 표시해야합니다.

그래서 이것을 테스트하기 위해 하나의 UIView와 두 개의 UITextField가있는 간단한 프로젝트를 만들었습니다. 문서별로,이 테스트 프로젝트에서 내가하는 것은 UIAlertView를 표시하고 NO를 반환하는 것입니다. 여기 방법 :

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField { 
    // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end 
    NSLog(@"In function: textFieldShouldEndEditing:(UITextField *)textField (tag=%i)", textField.tag); 
    [self logFirstResponder]; 

    // PRETEND THAT THERE IS AN ISSUE THAT FAILS VALIDATION AND DISPLAY 
    // A UIALERTVIEW. 
    UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Uh Oh!",@"") 
                 message:@"This is a test error" 
                 delegate:self 
               cancelButtonTitle:NSLocalizedString(@"OK",@"") 
               otherButtonTitles:nil]; 
    [errorAlert show]; 
    [errorAlert release]; 
    NSLog(@"Displaying Error UIAlertView!!!"); 

    // SINCE THE VALIDATION FAILED, RETURN NO TO HOLD THE USER IN THE 
    // UITEXTFIELD. 
    return NO; 
} 

그리고 여기에 문제가있다 : 다른 위에 하나의 UITextField에서 사용자가 클릭,이 방법은 3 회를 호출하면 그 결과로 UIAlertView는 3 회 표시됩니다. 다음은 내 테스트의 콘솔 로그입니다.

-- Field One tag = 100, Field Two tag = 200 -- 

2010-07-02 09:52:57.971 test project[22866:207] In function: textFieldShouldBeginEditing:(UITextField *)textField (tag=100) 
2010-07-02 09:52:57.977 test project[22866:207] In function: textFieldDidBeginEditing:(UITextField *)textField (tag=100) 
2010-07-02 09:52:57.977 test project[22866:207] Field One is the First Responder. 

-- now i'm going to click from Field One into Field Two -- 

2010-07-02 09:53:18.771 test project[22866:207] In function: textFieldShouldBeginEditing:(UITextField *)textField (tag=200) 
2010-07-02 09:53:18.772 test project[22866:207] Field One is the First Responder. 
2010-07-02 09:53:18.774 test project[22866:207] In function: textFieldShouldEndEditing:(UITextField *)textField (tag=100) 
2010-07-02 09:53:18.774 test project[22866:207] Field One is the First Responder. 
2010-07-02 09:53:18.778 test project[22866:207] Displaying Error UIAlertView!!! 
2010-07-02 09:53:18.780 test project[22866:207] In function: textFieldShouldBeginEditing:(UITextField *)textField (tag=200) 
2010-07-02 09:53:18.781 test project[22866:207] Field One is the First Responder. 
2010-07-02 09:53:18.781 test project[22866:207] In function: textFieldShouldEndEditing:(UITextField *)textField (tag=100) 
2010-07-02 09:53:18.782 test project[22866:207] Field One is the First Responder. 
2010-07-02 09:53:18.783 test project[22866:207] Displaying Error UIAlertView!!! 

그래서 거래가 무엇입니까? 그것은 뭔가를 놓친 것 같습니다 ... 어떻게 UITextField 유효성을 검사하고 오류를 제대로 표시합니까?

답변

8

UIAlert를 표시하는 대신 텍스트 필드의 오른쪽에 오류 아이콘을 표시 할 수 있습니다. 이렇게하면 3 번 발생해도 경고가 나타나지 않으며 사용자는이 아이콘이 3 번 설정되었음을 알 수 없습니다. 내가 한 일은 오류를 나타내는 이미지가있는 단추로 올바른보기를 설정하는 것입니다. 나는 무엇이 잘못되었는지 사용자에게 알려주는 경고를 보여주는 액션과 버튼을 연관시킨다. 나는 액션으로 이미지 뷰를 오른쪽 뷰에 추가하는 도우미 함수를 만들었다.

- (void)setErrorForTextField:(UITextField *)textField target:(id)target action:(SEL)selector 
{ 
    CGRect frame = CGRectMake(0.0, 0.0, 15.0, 28.0); 
    UIImage *image = [UIImage imageNamed:@"ErrorIcon.png"]; 
    UIButton *button = [[[UIButton alloc] initWithFrame:frame] autorelease]; 
    [button setImage:image forState:UIControlStateNormal]; 
    button.backgroundColor = [UIColor clearColor]; 

    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside]; 
    textField.rightView = button; 
    textField.rightViewMode = UITextFieldViewModeAlways; 
} 

내 ErrorIcon.png는 15x28 크기이므로 버튼 크기를 만듭니다. 버튼과 이미지가 텍스트 필드에 맞는지 확인합니다. 너무 큰 경우 올바른보기로 축소합니다. 나는 어떤 크기 조절도하지 않아도되는 적당한 크기로 설정했다.

위의 코드에 표시된 모드를 사용하여 올바른보기를 숨기거나 표시 할 수 있습니다. 하나의 모드는 항상 있고 다른 모드는 항상 있습니다. 탐색하려는 다른 모드가 있습니다.

이제 사용자가 텍스트 필드 편집을 완료하고 필요에 따라 오류를 설정할 때 각 필드를 평가할 수 있습니다. 또한 폼이 처리 될 때 발생하는 또 다른 일치하는 검증 세트가 있습니다. 유효성 검사를 위해 동일한 코드가 실행되도록 노력하고 싶습니다.하지만 아직까지 그렇게하지 않았습니다.

관련 문제