【问题标题】:Get current text field when keyboard was shown显示键盘时获取当前文本字段
【发布时间】:2014-10-12 23:32:18
【问题描述】:

我想在显示键盘时获取当前正在编辑的文本字段。我需要这个来确定帧动画的一些 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){}];
}

【问题讨论】:

  • @Dima 我想要 view.getCurrentlyFocusedField 之类的东西。使用这种方法,我必须遍历每个字段并调用 .isFirstResponder。此外,这在keyboardWillShow 中被调用。这不会使键盘成为第一响应者,而不是启动 IBAction 的文本字段吗?
  • 创建一个属性,每次文本字段变为活动或不活动时更新,并使用它来使其更简单。
  • @Dima 这是否意味着没有办法获取当前活动的 UI 组件?
  • 是的,您可以找到文本字段

标签: ios objective-c keyboard uitextfield


【解决方案1】:

使用你的 UITextField 的 Delegates 并实现你的

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

创建一个 UITextField 变量UITextField *flagTextField;

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

现在你有了 textfield 的实例

【讨论】:

    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 2021-03-26
    相关资源
    最近更新 更多