简体   繁体   English

IOS:键盘出现时将TextField向上移动

[英]IOS: Move TextField Up When Keyboard Appears

I am using the following method to move the view upwards when the keyboard appears so the keyboard does not block a textfield. 我使用以下方法在键盘出现时将视图向上移动,以便键盘不会阻止文本字段。 Basically, I embed the textfields in a scrollview and scroll upwards when the keyboard appears. 基本上,我将文本字段嵌入到滚动视图中,并在出现键盘时向上滚动。

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, _activeField.frame.origin) ) {
        [_scrollView scrollRectToVisible:_activeField.frame animated:YES];
    }
}

However, when the textfield is already at the top of the view and there is no need for it to jump up, the above code causes it to jump up out of view. 但是,当文本字段已经位于视图的顶部并且不需要向上跳转时,上面的代码将导致其跳出视图。

Somewhere I recall reading that there is a line you can add to prevent that but I can't remember it. 我记得在某处您可以添加一行来防止这种情况,但我不记得了。 Basically, it would test if the textfield is already high enough up that the keyboard won't cover it and therefore, the view does not need to be moved. 基本上,它将测试文本字段是否已经足够高到足以使键盘无法覆盖它,因此不需要移动视图。

The if statement in above code does not appear to be screening out cases where the textfield is not hidden. 上面代码中的if语句似乎并未筛选出未隐藏文本字段的情况。

Can anyone suggest a way to do this? 有人可以建议一种方法吗?

Thank you. 谢谢。

If you are using autolayout, you should use constraints to manipulate the view instead of frames. 如果使用自动布局,则应使用约束而不是框架来操纵视图。 You could try manipulating the bottom spacing of your textField or view to its superview as per your need and putting the layoutIfNeeded call inside an animation block. 您可以根据需要尝试操纵textField的底部间距或查看其超级视图,然后将layoutIfNeeded调用放入动画块中。 Also you can check if the value of your bottom constraint is already a particular value or pass a bool on UIKeyboardWillHideNotification and UIKeyboardWillShowNotification , if it is, then the value of the constraint should not change. 您还可以检查底部约束的值是否已经是特定值,或者在UIKeyboardWillHideNotificationUIKeyboardWillShowNotification上传递布尔值(如果是),则约束的值不应更改。 Something like: 就像是:

-(void)showViewAnimatedly:(BOOL)show{

    if(show){
        [bottomConstraint setConstant:0];
    }else{
        [bottomConstraint setConstant:-160];
    }

    [UIView animateWithDuration:0.3f animations:^{

        [self.view layoutIfNeeded];

    }];
}

I would also recommend using UIKeyboardWillShowNotification instead of UIKeyboardDidShowNotification as the transition seems more in tune with the keyboard appearing. 我还建议您使用UIKeyboardWillShowNotification而不是UIKeyboardDidShowNotification因为过渡似乎与键盘的出现更加UIKeyboardDidShowNotification UIKeyboardDidShowNotification will start the transition AFTER keyboard appears. UIKeyboardDidShowNotification将在出现键盘后开始过渡。

Check out 'IQKeyboardManager'. 签出“ IQKeyboardManager”。 It is an excellent control for your requirements. 它是满足您要求的绝佳控件。 And it requires only one line of code from you. 而且您只需要一行代码。 It works for both UITextFields and UITextViews. 它适用于UITextFields和UITextViews。 It also has the option for previous and next buttons. 它还具有上一个和下一个按钮的选项。 You can install it in your project as a cocoapod 您可以将它作为cocoapod安装在项目中

https://www.cocoacontrols.com/controls/iqkeyboardmanager https://www.cocoacontrols.com/controls/iqkeyboardmanager

its simple when keyboard appears change the y axis co-ordinate of your textview or textfield with animation if requires. 它很简单,当需要出现键盘时,可以通过动画更改文本视图或文本字段的y轴坐标。 The code you can refer is below----> 您可以参考的代码如下---->

-(void)keyboardWillShow {
    // Animate the current view out of the way
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)keyboardWillHide {
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    if ([sender isEqual:mailTf])
    {
        //move the main view, so that the keyboard does not hide it.
        if  (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:YES];
        }
    }
}

//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view

    CGRect rect = self.view.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.view.frame = rect;

    [UIView commitAnimations];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillHide)
                                             name:UIKeyboardWillHideNotification
                                           object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                             name:UIKeyboardWillHideNotification
                                           object:nil];
}

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

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