Swift 解決鍵盤(pán)遮蓋問(wèn)題封裝

日常開(kāi)發(fā)中,經(jīng)常會(huì)遇到輸入框被鍵盤(pán)遮蓋的問(wèn)題, 本次思路是 將鍵盤(pán)處理相關(guān)代碼封裝成一個(gè) 單利的工具類(lèi), 通過(guò)監(jiān)聽(tīng)系統(tǒng)的鍵盤(pán)相關(guān)通知來(lái) 獲取鍵盤(pán)信息,實(shí)現(xiàn)被遮蓋視圖的上移操作,上代碼:

import Foundation
class KeyBoderHandleTool: NSObject {
    
    //可能會(huì)被遮蓋的 view
    private var keyBoderHandleView :UIView?
    
    //可能會(huì)被遮蓋的view 的遮蓋高度
    private var keyBoderHandleHeigt :CGFloat = 0.0
    private let disposeBag = DisposeBag()
    
    //單利對(duì)象
    private static var sharedTool :KeyBoderHandleTool?
    
    //獲取單利對(duì)象
    class func getSharedKeyBoderTool() ->KeyBoderHandleTool{
        
        guard let instance = sharedTool else {
            sharedTool = KeyBoderHandleTool()
            return sharedTool!
        }
        return instance
    }
    
    
    //銷(xiāo)毀單利對(duì)象
    class func destroy() {
        sharedTool = nil
    }

    // 私有化init 初始方法
    private override init() {}
    
    
    //監(jiān)聽(tīng)鍵盤(pán)彈出
    /// 處理鍵盤(pán) 遮蓋問(wèn)題
    ///
    /// - Parameters:
    ///   - handleView: 需要處理的視圖
    ///   - offsetY: 如果是 可滑動(dòng)的view  就傳入 y 軸上的偏移量
    func handleKeyBoderAction(handleView :UIView, offsetY :CGFloat?){
        
        if keyBoderHandleView != nil {
            //更換遮蓋view
            self.keyBoderHandleView = handleView
            return
        }
        
        print("開(kāi)始了****************")
        self.keyBoderHandleView = handleView
        
        //監(jiān)聽(tīng)鍵盤(pán)出現(xiàn)
        weak var weakSelf = self
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: OperationQueue.main) { (notification) in
            
            let info = notification.userInfo
            
            //鍵盤(pán)動(dòng)畫(huà)時(shí)間
            let duration = (info?[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
            
            //鍵盤(pán)坐標(biāo)尺寸
            let keyBoderRect = (info?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
            //獲取鍵盤(pán)被遮蓋部分的高度
            let keyBoderHeight = keyBoderRect.size.height      //獲取鍵盤(pán)高度
            let boundHeight = UIScreen.main.bounds.size.height  //屏幕高度
            
            let viewMaxY :CGFloat = offsetY == nil ? weakSelf!.keyBoderHandleView!.frame.maxY : (weakSelf!.keyBoderHandleView!.frame.maxY-offsetY!)
            //需要處理的 view 的絕對(duì) Y 坐標(biāo)
            
            //計(jì)算出被遮蓋部分的高度
            weakSelf!.keyBoderHandleHeigt = viewMaxY - (boundHeight-keyBoderHeight)
            if weakSelf!.keyBoderHandleHeigt <= 0 {
                return
            }
            
            //將其父視圖 上移被遮蓋的高度
            if let superView = weakSelf!.keyBoderHandleView!.superview {
                
                UIView.animate(withDuration: duration, animations: {
                    weakSelf!.keyBoderHandleView!.superview!.frame = CGRect.init(x: superView.frame.origin.x, y: superView.frame.origin.y - weakSelf!.keyBoderHandleHeigt, width: superView.bounds.size.width, height: superView.bounds.size.height)
                    
                })
                
            }
            print("打印數(shù)據(jù)--消失--\(weakSelf!.keyBoderHandleHeigt)----\(weakSelf!.keyBoderHandleView!.tag)")
            
        }
        
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: OperationQueue.main) { (notification) in
            
            let info = notification.userInfo
            if weakSelf!.keyBoderHandleHeigt <= 0{
                return
            }
            
            //鍵盤(pán)動(dòng)畫(huà)時(shí)間
            let duration = (info?[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
            
            //將高度還原
            if let superView = weakSelf!.keyBoderHandleView!.superview {
                UIView.animate(withDuration: duration, animations: {
                    weakSelf!.keyBoderHandleView!.superview!.frame = CGRect.init(x: superView.frame.origin.x, y: superView.frame.origin.y + weakSelf!.keyBoderHandleHeigt, width: superView.bounds.size.width, height: superView.bounds.size.height)
                    
                })
            }
            
            print("打印數(shù)據(jù)--消失--\(weakSelf!.keyBoderHandleHeigt)----\(weakSelf!.keyBoderHandleView!.tag)")
            
        }
    }

    deinit {
        
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
    }
}

使用時(shí), 只需要直接調(diào)用:

KeyBoderHandleTool.getSharedKeyBoderTool().handleKeyBoderAction(handleView: textField, offsetY: nil)

當(dāng)輸入框在 可滑動(dòng)控件上時(shí),記得傳入 y 軸上的 offset,否則傳nil

注意點(diǎn):

1:在 確定不需要再監(jiān)聽(tīng)的情況下可以 調(diào)用 工具類(lèi)中的 銷(xiāo)毀方法
2: 發(fā)生界面跳轉(zhuǎn)等情況時(shí),請(qǐng)先將鍵盤(pán)隱藏(self.view.endEditing(true))

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言 本博客轉(zhuǎn)載自瀟瀟鳳兒 傳送門(mén) 在開(kāi)發(fā)中,經(jīng)常會(huì)遇到鍵盤(pán)擋住輸入框的情況,比如登錄界面或注冊(cè)界面,彈出的軟鍵...
    傲嬌的狗蛋閱讀 5,721評(píng)論 2 42
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類(lèi)型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,689評(píng)論 1 32
  • 2017.02.22 可以練習(xí),每當(dāng)這個(gè)時(shí)候,腦袋就犯困,我這腦袋真是神奇呀,一說(shuō)讓你做事情,你就犯困,你可不要太...
    Carden閱讀 1,500評(píng)論 0 1
  • 一個(gè)人只要思想健在 靈魂便永遠(yuǎn)豐滿(mǎn)
    Xx山茶閱讀 145評(píng)論 0 0
  • 記得遇見(jiàn)你的第一天,是個(gè)下著鵝毛大雪的冬天,那是我的略胖,小個(gè)子,是個(gè)有點(diǎn)自卑,不起眼的小姑娘。那天遇見(jiàn)和...
    夢(mèng)想家小亞亞閱讀 321評(píng)論 3 0

友情鏈接更多精彩內(nèi)容