简体   繁体   English

当键盘出现在 iOS 中时向上移动 UIView

[英]Move UIView up when the keyboard appears in iOS

I have a UIView, it is not inside UIScrollView.我有一个 UIView,它不在 UIScrollView 里面。 I would like to move up my View when the keyboard appears.当键盘出现时,我想向上移动我的视图。 Before I tried to use this solution: How can I make a UITextField move up when the keyboard is present?在我尝试使用此解决方案之前: 当键盘存在时,如何使 UITextField 向上移动? . .

It was working fine.它工作正常。 But after inserting the data in the textfields, it takes me to another view, and when I get back to this page, its just jumping, and I couldn't see my text fields.但是在文本字段中插入数据后,它把我带到另一个视图,当我回到这个页面时,它只是跳跃,我看不到我的文本字段。 Is there any better solution for this problem?这个问题有没有更好的解决方案?

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[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];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - keyboard movements
- (void)keyboardWillShow:(NSNotification *)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = -keyboardSize.height;
        self.view.frame = f;
    }];
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = 0.0f;
        self.view.frame = f;
    }];
}

Use the following code in order to show and hide the keyboard使用以下代码来显示和隐藏键盘

//Declare a delegate, assign your textField to the delegate and then include these methods

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    return YES;
}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];

    [self.view endEditing:YES];
    return YES;
}


- (void)keyboardDidShow:(NSNotification *)notification
{
    // Assign new frame to your view 
    [self.view setFrame:CGRectMake(0,-110,320,460)]; //here taken -110 for example i.e. your view will be scrolled to -110. change its value according to your requirement.

}

-(void)keyboardDidHide:(NSNotification *)notification
{
    [self.view setFrame:CGRectMake(0,0,320,460)];
}

I wrote a little category on UIView that manages temporarily scrolling things around without needing to wrap the whole thing into a UIScrollView .我在UIView上写了一个小类别,它可以管理临时滚动的东西,而无需将整个东西包装到UIScrollView My use of the verb "scroll" here is perhaps not ideal, because it might make you think there's a scroll view involved, and there's not--we're just animating the position of a UIView (or UIView subclass).我在这里使用的动词“滚动”可能并不理想,因为它可能会让您认为涉及到滚动视图,而实际上并没有——我们只是在为UIView (或UIView子类)的位置设置动画。

There are a bunch of magic numbers embedded in this that are appropriate to my form and layout that might not be appropriate to yours, so I encourage tweaking this to fit your specific needs.其中嵌入了一堆适合我的形式和布局的神奇数字,但可能不适合您的形式和布局,因此我鼓励对其进行调整以满足您的特定需求。

UIView+FormScroll.h: UIView+FormScroll.h:

#import <Foundation/Foundation.h>

@interface UIView (FormScroll) 

-(void)scrollToY:(float)y;
-(void)scrollToView:(UIView *)view;
-(void)scrollElement:(UIView *)view toPoint:(float)y;

@end

UIView+FormScroll.m: UIView+FormScroll.m:

#import "UIView+FormScroll.h"


@implementation UIView (FormScroll)


-(void)scrollToY:(float)y
{

    [UIView beginAnimations:@"registerScroll" context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.4];
    self.transform = CGAffineTransformMakeTranslation(0, y);
    [UIView commitAnimations];

}

-(void)scrollToView:(UIView *)view
{
    CGRect theFrame = view.frame;
    float y = theFrame.origin.y - 15;
    y -= (y/1.7);
    [self scrollToY:-y];
}


-(void)scrollElement:(UIView *)view toPoint:(float)y
{
    CGRect theFrame = view.frame;
    float orig_y = theFrame.origin.y;
    float diff = y - orig_y;
    if (diff < 0) {
        [self scrollToY:diff];
    }
    else {
        [self scrollToY:0];
    }

}

@end

Import that into your UIViewController, and then you can do将它导入你的 UIViewController,然后你就可以了

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.view scrollToView:textField];
}

-(void) textFieldDidEndEditing:(UITextField *)textField
{
    [self.view scrollToY:0];
    [textField resignFirstResponder];
}

...or whatever. ...管他呢。 That category gives you three pretty good ways to adjust the position of a view.该类别为您提供了三种非常好的调整视图位置的方法。

Bind a view to keyboard is also an option (see GIF at the bottom of the answer)将视图绑定到键盘也是一个选项(请参阅答案底部的 GIF)

Swift 4斯威夫特 4

Use an extension: (Wasn't fully tested)使用扩展:(未完全测试)

extension UIView{
    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(UIView.keyboardWillChange(notification:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func unbindToKeyboard(){
        NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    @objc
    func keyboardWillChange(notification: Notification) {
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y+=deltaY

        },completion: nil)

    }
}

Swift 2 + 3斯威夫特 2 + 3

Use an extension:使用扩展名:

extension UIView{
    func bindToKeyboard(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UIView.keyboardWillChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }


    func keyboardWillChange(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let deltaY = targetFrame.origin.y - curFrame.origin.y


        UIView.animateKeyframesWithDuration(duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
                self.frame.origin.y+=deltaY

        },completion: nil)

    }  
}

Usage:用法:

// view did load...
textField.bindToKeyboard()

... ...

// view unload
textField.unbindToKeyboard()

result:结果:
在此处输入图片说明

important重要的
Don't forget to remove the observer when view is unloading卸载视图时不要忘记移除观察者

I found theDuncs answer very useful and below you can find my own (refactored) version:我发现theDuncs 的回答非常有用,您可以在下面找到我自己的(重构)版本:


Main Changes主要变化

  1. Now getting the keyboard size dynamically , rather than hard coding values现在动态获取键盘大小,而不是硬编码值
  2. Extracted the UIView Animation out into it's own method to prevent duplicate code将 UIView 动画提取到它自己的方法中以防止重复代码
  3. Allowed duration to be passed into the method, rather than being hard coded允许将持续时间传递给方法,而不是硬编码

- (void)viewWillAppear:(BOOL)animated {
    [[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 {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    float newVerticalPosition = -keyboardSize.height;

    [self moveFrameToVerticalPosition:newVerticalPosition forDuration:0.3f];
}


- (void)keyboardWillHide:(NSNotification *)notification {
    [self moveFrameToVerticalPosition:0.0f forDuration:0.3f];
}


- (void)moveFrameToVerticalPosition:(float)position forDuration:(float)duration {
    CGRect frame = self.view.frame;
    frame.origin.y = position;

    [UIView animateWithDuration:duration animations:^{
        self.view.frame = frame;
    }];
}

Based on Daniel Krom's solution.基于 Daniel Krom 的解决方案。 This is version in swift 3.0 .这是swift 3.0 中的版本。 Works great with AutoLayout , and moves whole view when keyboard appears.AutoLayout配合使用效果很好,并在键盘出现时移动整个视图。

extension UIView {

    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func unbindFromKeyboard(){
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc
    func keyboardWillChange(notification: NSNotification) {

        guard let userInfo = notification.userInfo else { return }

        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        })
    }  
}

How to use it: Add bindToKeyboard function in viewDidLoad like:如何使用它:在viewDidLoad添加bindToKeyboard函数,如:

override func viewDidLoad() {
    super.viewDidLoad()

    view.bindToKeyboard()
}

And add unbindFromKeyboard function in deinit:并在 deinit 中添加unbindFromKeyboard函数:

deinit {
    view.unbindFromKeyboard()
}

Swift 5斯威夫特 5

Updated version of answer by Daniel Krom above:上面 Daniel Krom 的更新版本的答案:

extension UIView {

    func bindToKeyboard() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(UIView.keyboardWillChange(notification:)),
            name: UIResponder.keyboardWillChangeFrameNotification,
            object: nil
        )
    }

    func unbindToKeyboard() {
        NotificationCenter.default.removeObserver(
            self,
            name: UIResponder.keyboardWillChangeFrameNotification,
            object: nil
        )
    }

    @objc func keyboardWillChange(notification: Notification) {
        let duration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        })
    }

}

For all the issue related to KeyBoard just use IQKeyBoardManager it's helpful.对于与 KeyBoard 相关的所有问题,只需使用 IQKeyBoardManager 即可。 https://github.com/hackiftekhar/IQKeyboardManager . https://github.com/hackiftekhar/IQKeyboardManager

try this one:-试试这个:-

 [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector (keyboardDidShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];


[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector (keyboardDidHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];

-(void) keyboardDidShow: (NSNotification *)notif
    {
        CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
        UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height+[self getTableView].tableFooterView.frame.size.height, 0.0);

        [self getTableView].contentInset = contentInsets;
        [self getTableView].scrollIndicatorInsets = contentInsets;

        CGRect rect = self.frame; rect.size.height -= keyboardSize.height;
        if (!CGRectContainsPoint(rect, self.frame.origin))
        {
            CGPoint scrollPoint = CGPointMake(0.0, self.frame.origin.y - (keyboardSize.height - self.frame.size.height));
            [[self getTableView] setContentOffset:scrollPoint animated:YES];
        }
    }

-(void) keyboardDidHide: (NSNotification *)notif
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    [self getTableView].contentInset = contentInsets;
    [self getTableView].scrollIndicatorInsets = contentInsets;
}

Based on theDunc's answer but written in Swift with Autolayout.基于theDunc 的回答,但使用自动布局用 Swift 编写。

@IBOutlet weak var bottomConstraint: NSLayoutConstraint! // connect the bottom of the view you want to move to the bottom layout guide

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self,
                                                     selector: #selector(ConversationViewController.keyboardWillShow(_:)),
                                                     name: UIKeyboardWillShowNotification,
                                                     object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self,
                                                     selector: #selector(ConversationViewController.keyboardWillHide(_:)),
                                                     name: UIKeyboardWillHideNotification,
                                                     object: nil)
}

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
    super.viewWillDisappear(animated)
}

// MARK: - Keyboard events

func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo,
        keyboardFrame = userInfo[UIKeyboardFrameBeginUserInfoKey]
    {
        let keyboardSize = keyboardFrame.CGRectValue().size
        self.bottomConstraint.constant = keyboardSize.height
        UIView.animateWithDuration(0.3) {
            self.view.layoutIfNeeded()
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    self.bottomConstraint.constant = 0
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

I have implemented a custom controller that dynamically calculates the size of the keyboard, scrolling textFields when it appears and disappears, even during rotation of the device.我已经实现了一个自定义控制器,它动态计算键盘的大小,在出现和消失时滚动 textFields,即使在设备旋转期间也是如此。 Works with all iOS devices.适用于所有 iOS 设备。 Just simply inherit the controller to have what you need.只需简单地继承控制器即可拥有您需要的东西。 You can find it with all the instructions at the following link: https://github.com/mikthebig/ios-textfield-scroll您可以在以下链接中找到所有说明: https : //github.com/mikthebig/ios-textfield-scroll

Simple solution without adding observer notification无需添加观察者通知的简单解决方案

-(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)textFieldDidEndEditing:(UITextField *)sender
{
     if  (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:NO];
        }
}

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

Where在哪里

#define kOFFSET_FOR_KEYBOARD 80.0

Here you go.干得好。 I have used this code with UIView, though.不过,我已将此代码与 UIView 一起使用。 You should be able to make those adjustments for scrollview.您应该能够对滚动视图进行这些调整。

    func addKeyboardNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillShow(notification:)),
                                               name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillHide(notification:)),
                                               name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
// if using constraints            
// bottomViewBottomSpaceConstraint.constant = keyboardSize.height
self.view.frame.origin.y -= keyboardSize.height
            UIView.animate(withDuration: duration) {
                self.view.layoutIfNeeded()
            }
        }
    }
    func keyboardWillHide(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
//if using constraint
//        bottomViewBottomSpaceConstraint.constant = 0
self.view.frame.origin.y = 0
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }

Don't forget to remove notifications at right place.不要忘记在正确的位置删除通知。

func removeKeyboardNotifications() {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

Swift 4斯威夫特 4

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillChangeFrame, object: nil)

@objc func keyboardWillChange(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.YourView.frame.origin.y+=deltaY
        },completion: nil)
    }

Just in case someone is looking for solution in Swift , throw this in your code:以防万一有人在Swift 中寻找解决方案,请将其放入您的代码中:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}


@objc func keyboardWillShow(notification: Notification) {
    if let userInfo = notification.userInfo {
        if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            UIView.animate(withDuration: 0.3) {
                var alteredFrame = self.view.frame
                alteredFrame.origin.y = -keyboardSize.height
                self.view.frame = alteredFrame
            }
        }
    }
}

@objc func keyboardWillHide(notification: Notification) {
    UIView.animate(withDuration: 0.3) {
        var alteredFrame = self.view.frame
        alteredFrame.origin.y = 0.0
        self.view.frame = alteredFrame
    }
}

It can be done easily & automatically if that textfield is in a table's cell (even when the table.scrollable = NO ).如果该textfield位于表格的单元格中(即使table.scrollable = NO ),也可以轻松自动textfield

NOTE that: the position and size of the table must be reasonable.注意:桌子的位置和大小必​​须合理。 eg:例如:

  • if the y position of table is 100 counted from the view's bottom, then the 300 height keyboard will overlap the whole table.如果 table 的 y 位置从视图底部算起 100,那么 300 高的键盘将与整个 table 重叠。
  • if table's height = 10 , and the textfield in it must be scrolled up 100 when keyboard appears in order to be visible, then that textfield will be out of the table's bound.如果表的height = 10 ,并且当键盘出现时其中的textfield必须向上滚动 100 才能可见,那么该文本字段将超出表的范围。

Declare a delegate, assign your text field to the delegate and then include these methods.声明一个委托,将您的文本字段分配给该委托,然后包含这些方法。

Assuming you have a login form with email and password text fields, this code will fit perfectly:假设您有一个带有电子邮件和密码文本字段的登录表单,此代码将非常适合:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [self.emailTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if (self.emailTextField == textField) {
        [self.passwordTextField becomeFirstResponder];
    } else {
        [self.emailTextField resignFirstResponder];
        [self.passwordTextField resignFirstResponder];
    }
    return NO;
}
- (void)viewWillAppear:(BOOL)animated {
    [[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 {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - keyboard movements
- (void)keyboardWillShow:(NSNotification *)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = -0.5f * keyboardSize.height;
        self.view.frame = f;
    }];
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = 0.0f;
        self.view.frame = f;
    }];
}

i just created a lightweight keyboard handler to follow keyboard frame.我刚刚创建了一个轻量级的键盘处理程序来跟随键盘框架。

Usage:用法:

 self.keyboardHandler = [EDKeyboardHandler new];

  [self.keyboardHandler listenWithBlock:^(KeyboardInfo *model)
  {
    //adjust view positions according to keyboard position here
  }];

and the KeyboardInfo model has the following properties:并且 KeyboardInfo 模型具有以下属性:

typedef enum : NSUInteger {
    KeyboardStatusDidShow,
    KeyboardStatusWillShow,
    KeyboardStatusDidHide,
    KeyboardStatusWillHide,
} KeyboardStatus;

@interface KeyboardInfo:NSObject

@property (nonatomic,readonly) NSTimeInterval animationDuration;
@property (nonatomic,readonly) CGRect keyboardFrame;
@property (nonatomic,readonly) NSInteger animationCurve;
@property (nonatomic,readonly) KeyboardStatus status;

@end

check GitHub project for details and cocoaPods integration.查看GitHub项目了解详细信息和 cocoaPods 集成。

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

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