美文网首页
swift底部工具栏跟随键盘一起变化

swift底部工具栏跟随键盘一起变化

作者: 陈水寒 | 来源:发表于2017-11-02 14:03 被阅读35次

1、监听键盘通知

// 注册键盘弹出通知
NotificationCenter.default.addObserver(self, selector: #selector(GGComposeViewController.keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)

2、获取通知内的信息

@objc fileprivate func keyboardWillChangeFrame(note : Notification) {
        // 取出通知中有用的信息
        let userInfo = note.userInfo!
        // 键盘弹出的动画时间
        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        // 键盘最后的frame
        let keyBoardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

        //do something
    }

3、改变底部工具栏距离底部的约束

@objc fileprivate func keyboardWillChangeFrame(note : Notification) {
        // 取出通知中有用的信息
        let userInfo = note.userInfo!
        // 键盘弹出的动画时间
        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        // 键盘最后的frame
        let keyBoardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

        // 计算工具栏约束高度  工具栏距离底部的约束高度 = 屏幕的高度 - 键盘的Y值
        let margin = UIScreen.main.bounds.height - keyBoardFrame.origin.y
        
        // 添加动画效果
        tabBarBottomCons.constant = margin
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }

4、注销通知

相关文章

网友评论

      本文标题:swift底部工具栏跟随键盘一起变化

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