2011-11-23 3 views
2

iPhone 응용 프로그램에서 작업 중입니다. 보기 중 하나에 네 개의 텍스트 필드가 있습니다. 이 4 개의 텍스트 필드에는 숫자 패드 키보드를 사용할 텍스트 필드가 하나 있습니다. 그러나 숫자 패드 키보드에는 리턴 키가 없습니다. 그래서 다음 코드를 사용하여 프로그래밍 방식으로 "완료"버튼을 추가했습니다.숫자 패드 키보드 전용 버튼

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { 
    [[NSNotificationCenter defaultCenter] addObserver:self     
      selector:@selector(keyboardDidShow:) 
               name:UIKeyboardDidShowNotification object:nil];   
} else { 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(keyboardWillShow:) 
               name:UIKeyboardWillShowNotification object:nil]; 
} 

    - (void)addButtonToKeyboard { 
// create custom button 
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
doneButton.frame = CGRectMake(0, 163, 106, 53); 
doneButton.adjustsImageWhenHighlighted = NO; 
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) { 
    [doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal]; 
    [doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted]; 
} else {   
    [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal]; 
    [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted]; 
} 
[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside]; 
// locate keyboard view 
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; 
UIView* keyboard; 
for(int i=0; i<[tempWindow.subviews count]; i++) { 
    keyboard = [tempWindow.subviews objectAtIndex:i]; 
    // keyboard found, add the button 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { 
     if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES) 
           [keyboard addSubview:doneButton];     
    } else { 
     if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) 
        [keyboard addSubview:doneButton]; 
     } 
    } 
    } 

    - (void)keyboardWillShow:(NSNotification *)note { 
// if clause is just an additional precaution, you could also dismiss it 
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 3.2) { 

     [self addButtonToKeyboard]; 


} 
    } 

     - (void)keyboardDidShow:(NSNotification *)note { 
// if clause is just an additional precaution, you could also dismiss it 
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { 

     [self addButtonToKeyboard]; 


     } 
    } 


- (void)doneButton:(id)sender { 
    NSLog(@"doneButton"); 
    NSLog(@"Input: %@", contactno.text); 

    [contactno resignFirstResponder]; 

    } 

이 텍스트 필드에는 문제가 없습니다. 그러나이 버튼은 나머지 텍스트 필드에도 추가됩니다. 어떻게 다른 텍스트 필드에 대해이 단추를 숨길 수 있습니다. enter image description here

미리 감사드립니다.

+0

http://cocoacontrols.com/platforms/ios/controls/amkeyboardnumberpad이 구현에서 살펴 해제 탭 이벤트를 캡처하고 원인 전체 UI를 통해 투명 UIView 추가 , 나를 위해 매우 잘 작동 –

+0

이 일을 정말 끔찍한 일입니다. 키보드의 구현이 변경되면 쉽게 깨질 수 있습니다. iPad에서는 작동하지 않으며 특히 iOS 5의 분할 키보드에서는 작동하지 않습니다. –

답변

23

하세요 제발 제발 제발 제발 제발하지 마세요 제발 제발. 이것은 너무 우스꽝 스럽습니다. 이것을 고려하십시오 :

  • 숫자 키패드의 레이아웃이 변경되면 어떻게됩니까?
  • 키 색상이 변경되면 어떻게됩니까?
  • 키보드의 구현이 더 이상 인덱스 1의 윈도우가 아닌 경우 어떻게해야합니까?
  • 키보드 및 주변 호스트의 구현이 변경되어 내부 설명이 바뀌면 어떻게 될까요?
  • iPad에서 키보드의 레이아웃이 완전히 다른 경우 어떻게해야합니까?

이것은 개인보기 계층 구조에 UI를 glomming하는 것과 관련된 수많은 문제 중 일부일뿐입니다.

이렇게하지 마십시오.

  1. 가에 -inputAccessoryView 속성을 사용하여 모든 UIResponder (따라서 모든 UIView)는 "완료"버튼으로 UIToolbar을 정의하려면 여기

대신이 개 대안이다. inputAccessoryView은 키보드가 움직이면서 활성화 될 때 키보드 위에 배치됩니다.

  • 키보드가

  • +15

    3. Apple에 번호판에 이미 완료 버튼을 추가하라는 버그 보고서를 제출하십시오. –

    +1

    @ JoshCaswell 그게 주어진다;) http://filearadar.com/ –

    +1

    그리고 클라이언트의 기대는 어떨까 ??? 그것은 또한 중요하다! !! – Maulik

    1

    전 세계 변수 UITextField * selectedTextField을 현재 사용자가 선택한 textField에 대한 포인터 (약한 참조)로 유지한다고 가정합니다. 보기의 모든 UITextField 개체에 IBOutlets을 저장하십시오 (강력한 참조). 그런 다음 큰 경우 절에 전체 addButtonToKeyboard 몸을 감싸는 :

    if (self.selectedTextField == self.contactNumberTextField){ 
        // ... add button 
    } 
    

    당신은

    - (void)textFieldDidBeginEditing:(UITextField *)textField; 
    

    는 현재 하나를 선택하는에 textField 알 UITextField 위임 방법을 설정해야합니다.

    사실 나는 콘센트가 없어도 selectedTextField.keyboardType 속성을 사용하여이 작업을 수행 할 수 있다고 생각하지만, 사용자 입력을 읽어야하기 때문에 콘센트가 이미있을 것입니다.

    희망이 도움이됩니다.

    1

    이 코드를 프로젝트에 넣고 텍스트 필드의 iboutlet을 설정하면됩니다. 사용하지 않는 메소드도 있지만 사용하지 않은 메소드는 제거합니다. 그러면 완료 버튼을 얻는 것입니다. 제발 제발 제발 제발 숫자 패드 키보드

    .H 파일

    @interface aaaViewController : UIViewController 
    { 
    IBOutlet UITextField *txthello; 
    UIImage *numberPadDoneImageNormal; 
    UIImage *numberPadDoneImageHighlighted; 
    UIButton *numberPadDoneButton; 
    
    } 
    
    @property (nonatomic, retain) UIImage *numberPadDoneImageNormal; 
    @property (nonatomic, retain) UIImage *numberPadDoneImageHighlighted; 
    @property (nonatomic, retain) UIButton *numberPadDoneButton; 
    

    하는 .m 파일

    - (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 
    
    // Add listener for keyboard display events 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { 
        [[NSNotificationCenter defaultCenter] addObserver:self 
                  selector:@selector(keyboardDidShow:) 
                   name:UIKeyboardDidShowNotification 
                   object:nil];  
    } else { 
        [[NSNotificationCenter defaultCenter] addObserver:self 
                  selector:@selector(keyboardWillShow:) 
                   name:UIKeyboardWillShowNotification 
                   object:nil]; 
    } 
    
    // Add listener for all text fields starting to be edited 
    [[NSNotificationCenter defaultCenter] addObserver:self 
                 selector:@selector(textFieldDidBeginEditing:) 
                  name:UITextFieldTextDidBeginEditingNotification 
                  object:nil]; 
    } 
    
    - (void)viewWillDisappear:(BOOL)animated { 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { 
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                    name:UIKeyboardDidShowNotification 
                    object:nil];  
    } else { 
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                    name:UIKeyboardWillShowNotification 
                    object:nil]; 
    } 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                   name:UITextFieldTextDidBeginEditingNotification 
                   object:nil]; 
    [super viewWillDisappear:animated]; 
    } 
    
    - (UIView *)findFirstResponderUnder:(UIView *)root { 
    if (root.isFirstResponder) 
        return root;  
    for (UIView *subView in root.subviews) { 
        UIView *firstResponder = [self findFirstResponderUnder:subView];   
        if (firstResponder != nil) 
         return firstResponder; 
    } 
    return nil; 
    } 
    
    - (UITextField *)findFirstResponderTextField { 
    UIResponder *firstResponder = [self findFirstResponderUnder:[self.view window]]; 
    if (![firstResponder isKindOfClass:[UITextField class]]) 
        return nil; 
    return (UITextField *)firstResponder; 
    } 
    
    - (void)updateKeyboardButtonFor:(UITextField *)textField { 
    
    // Remove any previous button 
    [self.numberPadDoneButton removeFromSuperview]; 
    self.numberPadDoneButton = nil; 
    
    // Does the text field use a number pad? 
    if (textField.keyboardType != UIKeyboardTypeNumberPad) 
        return; 
    
    // If there's no keyboard yet, don't do anything 
    if ([[[UIApplication sharedApplication] windows] count] < 2) 
        return; 
    UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; 
    
    // Create new custom button 
    self.numberPadDoneButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    self.numberPadDoneButton.frame = CGRectMake(0, 163, 106, 53); 
    self.numberPadDoneButton.adjustsImageWhenHighlighted = FALSE; 
    [self.numberPadDoneButton setTitle:@"Return" forState:UIControlStateNormal]; 
    // [self.numberPadDoneButton setFont:[UIFont boldSystemFontOfSize:18]]; 
    [self.numberPadDoneButton setTitleColor:[UIColor colorWithRed:77.0f/255.0f green:84.0f/255.0f blue:98.0f/255.0f alpha:1.0] forState:UIControlStateNormal]; 
    
    [self.numberPadDoneButton setImage:self.numberPadDoneImageNormal forState:UIControlStateNormal]; 
    [self.numberPadDoneButton setImage:self.numberPadDoneImageHighlighted forState:UIControlStateHighlighted]; 
    [self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside]; 
    
    // Locate keyboard view and add button 
    NSString *keyboardPrefix = [[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2 ? @"<UIPeripheralHost" : @"<UIKeyboard"; 
    for (UIView *subView in keyboardWindow.subviews) { 
        if ([[subView description] hasPrefix:keyboardPrefix]) { 
         [subView addSubview:self.numberPadDoneButton]; 
         [self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside]; 
         break; 
        } 
    } 
    } 
    
    - (void)textFieldDidBeginEditing:(NSNotification *)note { 
    [self updateKeyboardButtonFor:[note object]]; 
    } 
    
    - (void)keyboardWillShow:(NSNotification *)note { 
    [self updateKeyboardButtonFor:[self findFirstResponderTextField]]; 
    } 
    
    - (void)keyboardDidShow:(NSNotification *)note { 
    [self updateKeyboardButtonFor:[self findFirstResponderTextField]]; 
    } 
    
    - (IBAction)numberPadDoneButton:(id)sender { 
    UITextField *textField = [self findFirstResponderTextField]; 
    [textField resignFirstResponder]; 
    } 
    
    
    - (void)dealloc { 
    [numberPadDoneImageNormal release]; 
    [numberPadDoneImageHighlighted release]; 
    [numberPadDoneButton release]; 
    [super dealloc]; 
    }