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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容