1. 键盘遮挡问题 的解决:

核心: 通过系统的通知 获取 键盘的高度尺寸, 再移动相应的视图;

得到键盘的 Frame 信息:
let eFrame = notification?.userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
企业微信截图_987c6631-4e19-4b09-a69a-ae2693295047.png
    1. 解析出键盘的高度:
import Foundation
import UIKit
// 全局用: 静态工具
struct TyeTool{
    
    static func yeGetKeyboardFrame(notification: Notification?) -> CGRect
    { // 得到键盘的信息:Frame
        guard let eUserInfo = notification?.userInfo, let eFrame = eUserInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
        else { return CGRect(x: 0, y: 0, width: 0, height: 0)}
        
        return eFrame
    }
}
    1. 监听键盘的弹窗与隐藏 (通知):
    //--- 系统通知监听 键盘显示和隐藏 : 解决 键盘遮挡输入框的问题:
    func yeAddNotificationForkeyboard(){
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(yeKeyboardWillShow(_:)),
                                               name: UIResponder.keyboardWillShowNotification, object: nil)
        
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(yeKeyboardWillHide(_:)),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    1. 根据得到的 键盘高度 移动相应的视图 :
    @objc func yeKeyboardWillShow(_ notification: Notification?)
    { // 键盘 弹出;
        print("---键盘 弹出--")
        // 1. 得到 键盘的高度:
        let eKeyboardFrame = TyeTool.yeGetKeyboardFrame(notification: notification)
        let eKeyboardH = eKeyboardFrame.height
        
        UIView.animate(withDuration: 0.3, delay: 0.0, animations: { [self] in
            self.eUITextField.frame.origin.y -= eKeyboardH
        }) { eBool in
            print("---动画完成--")
        }
    }
    @objc func yeKeyboardWillHide(_ notification: Notification?)
    { // 键盘 隐藏;
        print("---键盘 隐藏--")
        let eKeyboardFrame = TyeTool.yeGetKeyboardFrame(notification: notification)
        let eKeyboardH = eKeyboardFrame.height
        
        UIView.animate(withDuration: 0.3, delay: 0.0, animations: { [self] in
            self.eUITextField.frame.origin.y += eKeyboardH
        }) { eBool in
            print("---动画完成--")
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容