其他分享
首页 > 其他分享> > Swift 视图随键盘弹出向上移动

Swift 视图随键盘弹出向上移动

作者:互联网

主要是通过观察者监听来完成

import UIKit

class TFVC: UIViewController {

    
    override func viewDidLoad() {
        super.viewDidLoad()
        hideKeyboardWhenTappedAround()
        let tf = UITextField(frame: CGRect(x: 0, y: 0, width: 120, height: 44))
        tf.borderStyle = .roundedRect
        tf.center = view.center
        view.addSubview(tf)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillhide), name: UIResponder.keyboardWillHideNotification, object: nil)
        
    }
    // 对观察者进行释放
    deinit {
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    //键盘改变
    @objc func keyboardWillShow(_ sender: NSNotification) {
        //获取键盘的frame
        guard let keyboardFrame = (sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {
            return
        }
        //获取动画执行的时间
        var duration = sender.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
        if duration == nil { duration = 0.25 }
        var frame = view.frame
        frame.origin.y = -keyboardFrame.height
        UIView.animate(withDuration: 0.5) {
            self.view.frame = frame
        }
    }

    @objc func keyboardWillhide(_ sender: NSNotification) {
        var frame = view.frame
        frame.origin.y = 0
        UIView.animate(withDuration: 0.5) {
            self.view.frame = frame
        }
    }
}

标签:nil,frame,UIResponder,视图,键盘,NotificationCenter,Swift,self,view
来源: https://www.cnblogs.com/chaostudy/p/16446114.html