简体   繁体   English

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

[英]Get current text field when keyboard was shown

I want to get the current text field being edited when the keyboard was show. 我想显示键盘时正在编辑的当前文本字段。 I need this to determine some y values for a frame animation. 我需要它来确定帧动画的一些y值。 However, my keyboardWasShown method is running in the controller, so I can easily get the view but am uncertain how to get the correct text field. 但是,我的keyboardWasShown方法正在控制器中运行,因此我可以轻松获取视图,但不确定如何获取正确的文本字段。 I have two text fields on this view. 我在此视图上有两个文本字段。

//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){}];
}

use the Delegates of your UITextField and implement your 使用UITextField的Delegates并实现您的

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

create an UITextField variable UITextField *flagTextField; 创建一个UITextField变量UITextField *flagTextField;

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

Now you have the instance of textfield 现在您有了textfield的实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM