Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

uitextfield - Elegantly replace iPhone keyboard with UIPickerView

I have a table view that has embedded UITextFields for entering some data. It also has two other fields that popup a UIPickerView and a UIDatePicker - as demonstrated in the DateCell example from Apple.

Mostly it works but I can't figure out how to cleanly transition from the text field keyboard to the other pickers - one slides out, one slides in - it looks weird and the scroll position on the table view sometimes gets screwed up - with everything scrolled off the top.

What I'd like to do is replace the text field keyboard without it animating away and without it growing the table view back to full size.

Any clues?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, here is a screencapture showing how this looks.

Implement UITextFieldDelegate and display a "popup" containing a UIPickerView.

- (void)textFieldDidEndEditing:(UITextField *)textField {

    UIPickerView *picker = [[UIPickerView alloc] 
                                 initWithFrame:CGRectMake(0, 244, 320, 270)];
    picker.delegate = self;
    picker.dataSource = self;
    [self.view addSubview:picker];
    [picker release];
}

When the keyboard disappears, a picker view is then visible.

If you want to take this a bit further, you can animate the UIPickerView "slide in" like the keyboard.

- (void)viewDidLoad {

    //picker exists in the view, but is outside visible range
    picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 480, 320, 270)];
    picker.delegate = self;
    picker.dataSource = self;
    [self.view addSubview:picker];
    [picker release];
}

//animate the picker into view
- (void)textFieldDidEndEditing:(UITextField *)textField {

    [UIView beginAnimations:@"picker" context:nil];
    [UIView setAnimationDuration:0.5];

    picker.transform = CGAffineTransformMakeTranslation(0,-236);
    [UIView commitAnimations];

}

//animate the picker out of view
- (void)textFieldDidBeginEditing:(UITextField *)textField {

    [UIView beginAnimations:@"picker" context:nil];
    [UIView setAnimationDuration:0.5];

    picker.transform = CGAffineTransformMakeTranslation(0,236);
    [UIView commitAnimations];
}

//just hide the keyboard in this example
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...