用UIPickerView优雅地替换iPhone键盘

时间:2009-08-14 01:41:18

标签: iphone uitextfield uipickerview uidatepicker

我有一个表视图,它嵌入了UITextFields来输入一些数据。它还有另外两个弹出UIPickerView和UIDatePicker的字段 - 如Apple的DateCell示例所示。

大多数情况下它有效,但我无法弄清楚如何从文本字段键盘干净地过渡到其他选择器 - 一个滑出,一个滑入 - 它看起来很奇怪,桌面视图上的滚动位置有时会搞砸 - 所有内容都滚动到顶部。

我想要做的是更换文本字段键盘,不要让它动画化,也不要将表格视图恢复到完整尺寸。

任何线索?

2 个答案:

答案 0 :(得分:31)

首先,这是一个screencapture showing how this looks

实现UITextFieldDelegate并显示包含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];
}

当键盘消失时,可以看到选择器视图。

如果你想更进一步,你可以像键盘一样为UIPickerView“滑入”设置动画。

- (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;
}

答案 1 :(得分:29)

只需将UITextField的inputView属性设置为UIPickerView。