输入框随键盘弹出升高

import UIKit

class ViewController: UIViewController {

let SCREENW = UIScreen.main.bounds.width
let SCREENH = UIScreen.main.bounds.height

var commentBtn:UIButton!
var inputLineView:UIView!
var inputTextView:UITextView!
var layView:UIView?

var changeY:CGFloat!
var keyboardDuration:Double!

override func viewDidLoad() {
    super.viewDidLoad()
    //注册键盘的监听
    let notiCenter =  NotificationCenter.default
    notiCenter.addObserver(self, selector: #selector(keyBoardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    notiCenter.addObserver(self, selector: #selector(keyBoardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    //评论按钮
    commentBtn = UIButton(frame: CGRect(x: 100, y: 100 , width: 100, height: 100))
    commentBtn.setTitle("Comment", for: .normal)
    commentBtn.setTitleColor(UIColor.white, for: .normal)
    commentBtn.backgroundColor = UIColor.blue
    commentBtn.addTarget(self, action: #selector(CommentBtnClick), for: .touchUpInside)
    view.addSubview(commentBtn)
  
}

func keyBoardWillShow(notifction:NSNotification){
    let kbInfo = notifction.userInfo
    //获取键盘的size
    let kbRect = (kbInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    //键盘的y偏移量
    changeY = kbRect.origin.y - SCREENH
    
    //键盘弹出的时间
    keyboardDuration = kbInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double
    
    //界面偏移动画
    UIView.animate(withDuration: keyboardDuration) {
        self.inputLineView.transform = CGAffineTransform(translationX: 0, y: self.changeY - self.inputLineView.frame.height)
    }
}

func keyBoardWillHide(notifction:NSNotification){
    UIView.animate(withDuration: 0.25) {
        self.inputLineView.transform = CGAffineTransform(translationX: 0, y: self.SCREENH)
        self.layView?.isHidden = true
    }
}


func CommentBtnClick(){

    if inputLineView == nil{
        inputLineView = UIView(frame: CGRect(x: 0, y: SCREENH , width: SCREENW, height: 50))
        inputLineView.backgroundColor = UIColor.cyan
        view.addSubview(inputLineView)
 
        inputTextView = UITextView(frame: CGRect(x: 3, y: 3, width: SCREENW - 6, height: 44))
        inputTextView.layer.borderColor = UIColor.darkGray.cgColor
        inputTextView.layer.borderWidth = 1
        inputLineView.addSubview(inputTextView)
        inputTextView.becomeFirstResponder()
    } else {
        inputTextView.becomeFirstResponder()
    }
    
    if layView == nil{
        self.layView = UIView(frame: self.view.frame)
        layView?.backgroundColor = UIColor.gray
        layView?.alpha = 0.5
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapLayView))
        layView?.addGestureRecognizer(tap)
        self.view.insertSubview(layView!, belowSubview: inputLineView!)
    } else {
        layView?.isHidden = false
    }

}
//点击layView,收回键盘
func tapLayView(){
    self.inputTextView.resignFirstResponder()
}


}

你可能感兴趣的:(输入框随键盘弹出升高)