Как настроить клавиатуру для числового текстового поля и буквенного текстового поля?

У меня есть макет, в котором у меня есть два текстовых поля, одно для буквенного ввода, а другое для числового ввода. Я установил для них разные типы клавиатур, например, по умолчанию для буквенного текстового поля и числа для числового поля.

Я добавил кнопку «Готово» на цифровую клавиатуру. Тем не менее, у меня возникает проблема с клавиатурами, когда я сначала записываю числовой текст, затем он показывает готовую кнопку клавиатуры, в то время как я сначала записывал алфавитный текст, а затем записывал его в числовое текстовое поле, тогда он не добавляет кнопку готово на цифровой клавиатуре .

Как мне это решить?

Я использовал этот код, чтобы добавить кнопку на цифровой клавиатуре.

    -(void)viewWillAppear:(BOOL)animated
       {
        // Register for the events

        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector (keyboardDidShow:)  name: UIKeyboardDidShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidHide:) name: UIKeyboardDidHideNotification object:nil];

        keyboardVisible = NO;
        scroll_view.contentSize=CGSizeMake(320, 400);
       }



        - (void)keyboardDidShow:(NSNotification *)note {
        UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
        UIView* keyboard;
        for (keyboard in tempWindow.subviews) {
            if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
                if (numberPadShowing) {
                    [self addButtonToKeyboard];
                    return;                 
                    break;
                } else {
                    for (UIView *v in [keyboard subviews]){
                        if ([v tag]==123)
                            [v removeFromSuperview];
                    }
                }
        }
    }

    -

    (void) keyboardDidHide: (NSNotification *)notif 
   {
        // Is the keyboard already shown
        if (!keyboardVisible) {
            return;
        }
        // Keyboard is no longer visible
        keyboardVisible = NO;
    }

     -(void)doneButton 
   {
    UIScrollView *scrollView =[[UIScrollView alloc] init];
    scrollView=scroll_view;
    [scrollView setContentOffset:svos animated:YES]; 
    [myActiveTextField resignFirstResponder];
   }

        - (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)textFieldDidBeginEditing:(UITextField *)textField
       {
        myActiveTextField=textField;
        if (myActiveTextField==txt_hour_section || myActiveTextField==txt_minute_section || myActiveTextField==txt_transport_time){
            numberPadShowing=TRUE;
            UIScrollView *scrollView =[[UIScrollView alloc] init];
            scrollView=scroll_view;

            svos = scrollView.contentOffset;
            CGPoint pt;
            CGRect rc = [textField bounds];
            rc = [textField convertRect:rc toView:scrollView];
            pt = rc.origin;
            pt.x = 0;
            pt.y -= 60;
            [scrollView setContentOffset:pt animated:YES];           

        }
        else{
            numberPadShowing=FALSE;
        }
    }



     -(BOOL)textFieldShouldReturn:(UITextField *)textField
     {
        UIScrollView *scrollView =[[UIScrollView alloc] init];
        scrollView=scroll_view;
        [scrollView setContentOffset:svos animated:YES]; 
        [textField resignFirstResponder];
       return YES;
    }

Заранее спасибо ...


person ios    schedule 27.07.2012    source источник


Ответы (2)


Я думаю, ваша проблема в том, что вы нажимаете на числовое поле после нажатия на альфа-поле, а альфа-клавиатура уже видна. Поэтому, когда вы касаетесь числового поля (пока альфа-клавиатура все еще находится в поле зрения), оно не запускает событие «keyboardDidShow», поскольку клавиатура уже отображается из предыдущего поля (хотя и альфа-версии).

Попробуйте поместить свою логику кнопки «Готово» в метод делегата для события текстового поля textFieldDidBeginEditing для числового поля.

person ross_t    schedule 27.07.2012

Если мой первый ответ не работает в вашей реализации, вы можете подумать о реструктуризации и перейти к настройке inputAccessoryView вашего UITextField. Код в этих строках должен помочь (вы можете поместить это в свой наконечник viewDidLoad, а также обратите внимание, что вам нужно будет реализовать метод doneTapped самостоятельно);

// Create a UIToolbar object and set its style to be black and transparent
    numericInputAccessoryView_ = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    numericInputAccessoryView_.barStyle = UIBarStyleBlackTranslucent;

// The flexible space item will push the done button to the far right
    UIBarButtonItem *space = [[UIBarButtonItem alloc] 
    initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

// Make the done button, this is a system item so you don't need to set the title or anything. This will call a method called "doneTapped:(id)sender" when you tap it, you'll need to implement that yourself.
    UIBarButtonItem *done = [[UIBarButtonItem alloc]WithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTapped:)];

// Stick the flexible space and the done button in your toolbar    
    numericInputAccessoryView_.items = [NSArray arrayWithObjects:space,done, nil];

// This would return it, if you had this in a separate method. 
    return numericInputAccessoryView_;
person ross_t    schedule 27.07.2012