使用UIPicker和UIKeyboard的多个UITextField

时间:2012-06-26 17:06:55

标签: iphone ios uitextfield uipickerview

所以我有大约7个文本字段,其中6个使用键盘,另一个使用选择器。我遇到的问题是,如果触摸链接到拾取器的文本字段时键盘打开,键盘将不会被忽略,并且拾取器会出现在它下面。这是我的代码

- (void) textFieldDidBeginEditing:(UITextField *)textField
 {    
pickerView.hidden = YES;
if ([textField isEqual:state])
{   

    [state resignFirstResponder];
    [self textFieldFirstResponderOnDelay1];




}

else
{
    pickerView.hidden = YES;

    // This movie the view up so textfield isn't hidden by keyboard
    CGRect textFieldRect =
    [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect =
    [self.view.window convertRect:self.view.bounds fromView:self.view];

    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator =
    midline - viewRect.origin.y
    - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator =
    (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
    * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;

    if (heightFraction < 0.0)
    {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }

    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];

}





}


-(void) viewDidLoad
{
pickerView = [[UIPickerView alloc] init];
pickerView.frame = CGRectMake(0, 245, 320, 216);
pickerView.delegate = self;
pickerView.hidden = YES;
pickerView.showsSelectionIndicator = YES;
state.inputView = pickerView;

[self.view addSubview:pickerView];
}


-(void)textFieldFirstResponderOnDelay1
{ 
pickerView.hidden=NO;
[pickerView reloadAllComponents];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
if([textField isEqual:state])
{

}
else
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];

}




}

1 个答案:

答案 0 :(得分:2)

不是将pickerview添加为主窗口的子视图,只需将其设置为相应textview的输入视图,然后它将显示/隐藏为键盘正常:

textField.inputView = pickerView;