美文网首页
使用第三方键盘时,代理方法会被调用3次,可能会有bug,解决办法

使用第三方键盘时,代理方法会被调用3次,可能会有bug,解决办法

作者: 孤帆日记 | 来源:发表于2016-08-04 15:33 被阅读312次

    define WeakObj(o) __weak typeof(o) weak##o = o;

    @interface ViewController()@property(weak, nonatomic) IBOutlet NSLayoutConstraint * bottomCons;//textV距离屏幕底部的约束,默认设置为0

    @end

    • (void) viewDidLoad { [super viewDidLoad];

      // 监听键盘 将要 弹出和隐藏
      [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardWillShowOrHide: ) name: UIKeyboardWillShowNotification object: nil];

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

    }

    /** 第三方键盘将要显示时, 此方法会被调用 3次,键盘y坐标依次为0,226,292:
    2016-08-04 14:50:40.810 YZInputViewDemo[883:260581] 0.000000
    2016-08-04 14:50:40.976 YZInputViewDemo[883:260581] 226.000000
    2016-08-04 14:50:41.001 YZInputViewDemo[883:260581] 292.000000
    即将隐藏时,拿到的键盘高度是292,所以代码中直接写死为 0
    */

    • (void) keyboardWillShowOrHide: (NSNotification * ) note {

      //注意,字典里存放的都是对象,要把对象转为CGRect结构体,使用CGRectValue方法。
      CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
      CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

      WeakObj(self);
      NSLog(@"%f", keyboardFrame.size.height);

      warning: 修改底部视图距离底部的间距,

      之前下面方法放在keyboardWillChangeFrame:方法中,导致第3次292时,_bottomCons.constant == 0不成立,于是_bottomCons.constant被重新赋值为0!这就是bug原因。解决办法就是监听将要显示和将要消失两个通知!
      // _bottomCons.constant = (_bottomCons.constant == 0 ? endFrame.size.height :
      // 0);
      // 修改底部视图距离底部的间距
      if ([note.name isEqualToString: @"UIKeyboardWillHideNotification"]) {
      _bottomCons.constant = 0;
      } else { // willShow
      _bottomCons.constant = keyboardFrame.size.height;
      }

      [UIView animateWithDuration: duration animations: ^{ [weakself.view layoutIfNeeded];
      }];
      }

    @end

    相关文章

      网友评论

          本文标题:使用第三方键盘时,代理方法会被调用3次,可能会有bug,解决办法

          本文链接:https://www.haomeiwen.com/subject/utgcsttx.html