Search code examples
objective-cuitextfielduipickerview

UITextField with UIPickerView keyboard bug


I just want to ask if how can I prevent keyboard popping out when it's pressing the UITextField? I have a UITextField and UIPickerView if I press the UITextField for the first time it's fine, it's showing the UIPickerView but then after i select in the UIPickerView then press the textfield again, instead of showing the UIPickerView again it shows the keyboard? I have this method on my UITextField when you click it it shows the UIPickerView:

- (IBAction)clickText:(id)sender
{
    int tag = [(UITextField*)sender tag];
    self.myPicker.hidden = NO;
    selectedTable = tag;
    [sender resignFirstResponder];
    float yy = 10;
    switch (tag) {
        case 0: yy = self.txtLeasename.frame.origin.y + self.myPicker.frame.size.height;
            break;
        case 1: yy = self.txtFeet.frame.origin.y + self.myPicker.frame.size.height;
            break;
        case 2: yy = self.txtInches.frame.origin.y + self.myPicker.frame.size.height;
            break;
        default:
            break;
    }
}

How can i fix this kind of bug? Thank you very much!


Solution

  • Implement this Method and don't forget to assign the textfield.delegate to your controller

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
        // Check if the given textfield is your textfield with the date picker.
        if (textField.tag == 99) {
           // Then add your picker to your view
           UIDatePicker *pv = [[UIDatePicker alloc] initWithFrame:CGRectMakeZero];
           [self.view addSubview:pv]; 
    
           // And return NO
           return NO; // Return NO prevents your Textfield from showing the Keyboard
        }
    
        return YES;
    
    }
    

    This should work for you:

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
        int tag = textField.tag;
        selectedTable = tag;
        float yy = 10;
    
        switch (tag) {
            case 0: 
                self.myPicker.hidden = NO;
                return NO;
    
            case 1:
                self.myPicker.hidden = NO;
                return NO;
    
            case 2:
                self.myPicker.hidden = NO;
                return NO;
    
            default:
                self.myPicker.hidden = YES;
                return YES;
    
            }        
    }