用UIPickerView优雅地替换iPhone键盘

Bra*_*son 14 iphone uidatepicker uipickerview uitextfield

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

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

我想要做的是替换文本字段键盘,而不用它动画离开,没有它将表视图恢复到完整大小.

有线索吗?

ben*_*ord 31

首先,这是一个屏幕截图,显示了它的外观.

实现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];
}
Run Code Online (Sandbox Code Playgroud)

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

如果你想更进一步,你可以像键盘一样动画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;
}
Run Code Online (Sandbox Code Playgroud)

  • 就像一张纸条,这是执行此操作的旧方法.更"现代"的版本将使用textField的inputView属性. (12认同)

小智 29

只需将UITextField的inputView属性设置为UIPickerView即可.