天天看点

swift 5 中键盘遮挡输入框的解决办法

自定义输入框,检测键盘高度及开始编辑,结束编辑事件,达到自动升降输入框不被键盘遮挡

YYYSwiftTextField.swift

//
//  YYYSwiftTextField.swift
//  YYYSwiftProductTh
//
//  Created by YYY on 2021/2/5.
//

import UIKit

class YYYSwiftTextField: UITextField, UITextFieldDelegate {

    var keyboardheight:CGFloat = CGFloat.init()
    
    override init(frame: CGRect) {
         
        super.init(frame: frame)
        self.delegate = self
        self.clearButtonMode = .whileEditing

        NotificationCenter.default.addObserver(self, selector:  #selector(KeyBoardHeightchange(_:)) , name: NSNotification.Name(rawValue: UIResponder.keyboardDidShowNotification.rawValue), object: nil)
        

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func KeyBoardHeightchange(_ notification: Notification) {
        // 获取键盘信息
        let keyboardinfo:CGRect = notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! CGRect

        keyboardheight  = (keyboardinfo.size.height)
        
        print("键盘弹起")

        print(keyboardheight)
        
        self.textFieldDidBeginEditing(UITextField.init())

    }
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        //输入框不直接在UIScrollView上需要
//        let rect = self.superview?.convert(self.frame, to: self.superview)

          //设置中心点偏移
          UIView.animate(withDuration: 0.3) {
            
            if(self.keyboardheight <= 0){
                return
            }
            
            let superScrollowView:UIScrollView = self.superview as! UIScrollView
           
            //输入框距离底部的高度 tempHeight = keyboardheight + 20 + 20 + self.height
            let tempHeight = self.keyboardheight + 20 + 20 + self.height
            
            //输入框的bottom  kScreenHeight - gao +self.height
            
            //scrollow的偏移量
            superScrollowView.contentOffset = CGPoint.init(x: 0, y: self.top - (kScreenHeight - tempHeight) + self.height)
            
            
          }

    }
    
    @available(iOS 10.0, *)
    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
        
        UIView.animate(withDuration: 0.25) {

            let superView:UIScrollView = self.superview as! UIScrollView
            superView.contentOffset = CGPoint.init(x: 0, y: 0)

        }
    }
}