显示键盘时获取当前文本字段

时间:2014-08-19 18:38:26

标签: ios objective-c keyboard uitextfield

我想在键盘显示时获取当前正在编辑的文本字段。我需要这个来确定帧动画的y值。但是,我的keyboardWasShown方法在控制器中运行,因此我可以轻松获取视图但不确定如何获取正确的文本字段。我在这个视图上有两个文本字段。

//Move view to match keyboard when shown
-(void)keyboardWasShown:(NSNotification*)aNotification{

    //Get frame of keyboard
    NSValue* keyboardEndFrameValue = [[aNotification userInfo] objectForKey: UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardEndFrame = [keyboardEndFrameValue CGRectValue];

    //Get animation properties of keyboard
    NSNumber* animationDurationNumber = [[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration = [animationDurationNumber intValue];
    NSNumber* animationCurveNumber = [[aNotification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    UIViewAnimationCurve animationCurve = [animationCurveNumber intValue];
    UIViewAnimationOptions animationOptions = animationCurve << 16;

    //Set up animation
    [UIView animateWithDuration:animationDuration delay:0.0 options:animationOptions animations:^{
            CGRect viewFrame = self.view.frame;
            viewFrame.origin.y -= keyboardEndFrame.origin.y;
//I need the access to the text field here to determine y value.
            self.view.frame = viewFrame;
     } completion:^(BOOL finished){}];
}

1 个答案:

答案 0 :(得分:0)

使用您的UITextField的代表并实现您的

- (void)textFieldDidBeginEditing:(UITextField *)textField;

创建UITextField变量UITextField *flagTextField;

- (void)textFieldDidBeginEditing:(UITextField *)textField{
     flagTextField = textField;
}

现在你有了textfield的实例