IQKeyboardManagerSwift源码解析:Swift版本架构设计与核心类
概述
IQKeyboardManagerSwift是一个用于解决iOS键盘遮挡问题的库,它提供了简单的解决方案,可以自动调整输入框在键盘弹出时的位置,同时支持自定义规则和动画效果,具有很高的易用性和扩展性。本文将深入解析IQKeyboardManagerSwift的架构设计与核心类,帮助开发者更好地理解和使用这个库。
整体架构
IQKeyboardManagerSwift的整体架构采用了模块化的设计思想,主要包含以下几个核心模块:
- IQKeyboardManager:核心管理类,负责协调各个模块的工作,提供对外的API接口。
- Configuration:配置模块,包含各种配置类,用于管理键盘和输入框的相关配置。
- UIKitExtensions:UIKit扩展模块,为UIView、UIViewController等UIKit类提供扩展方法,方便获取父容器视图控制器等操作。
- IQKeyboardNotification:键盘通知模块,负责监听键盘的弹出、收起和变化等事件。
- IQTextInputViewNotification:输入框通知模块,负责监听输入框的编辑事件。
核心类解析
IQKeyboardManager
IQKeyboardManager是整个库的核心管理类,采用单例模式设计,通过shared属性获取实例。它主要负责启用/禁用键盘距离管理、设置键盘与输入框的距离、处理键盘事件等。
@MainActor
public static let shared: IQKeyboardManager = .init()
/**
Enable/disable managing distance between keyboard and textInputView.
Default is YES(Enabled when class loads in `+(void)load` method).
*/
public var isEnabled: Bool = false {
didSet {
guard isEnabled != oldValue else { return }
// If not enable, enable it.
if isEnabled {
// If keyboard is currently showing.
if activeConfiguration.keyboardInfo.isVisible {
adjustPosition()
} else {
restorePosition()
}
showLog("Enabled")
} else { // If not disable, disable it.
restorePosition()
showLog("Disabled")
}
}
}
IQActiveConfiguration
IQActiveConfiguration是活动配置类,负责管理键盘和输入框的当前状态,包括键盘信息、输入框信息、根控制器配置等。它通过IQKeyboardNotification和IQTextInputViewNotification来监听键盘和输入框的事件,并根据事件类型发送相应的通知。
internal final class IQActiveConfiguration: NSObject {
private let keyboardObserver: IQKeyboardNotification = .init()
private let textInputViewObserver: IQTextInputViewNotification = .init()
var rootConfiguration: IQRootControllerConfiguration?
var isReady: Bool {
if textInputViewInfo != nil,
let rootConfiguration = rootConfiguration {
return rootConfiguration.isReady
}
return false
}
}
UIView+Parent
UIView+Parent是UIView的扩展类,提供了parentContainerViewController()方法,用于获取当前视图所在的父容器视图控制器。这个方法会遍历视图的层级结构,找到最上层的容器视图控制器,方便后续的布局调整。
public extension IQKeyboardExtension where Base: UIView {
/**
Returns the UIViewController object that is actually the parent of this object.
Most of the time it's the viewController object which actually contains it,
but result may be different if it's viewController is added as childViewController of another viewController.
*/
func parentContainerViewController() -> UIViewController? {
// 实现代码省略
}
}
工作流程
IQKeyboardManagerSwift的工作流程主要包括以下几个步骤:
- 初始化:IQKeyboardManager在初始化时会创建IQActiveConfiguration实例,并添加键盘和输入框的通知监听。
- 事件监听:当键盘弹出、收起或输入框开始编辑时,IQActiveConfiguration会接收到相应的通知,并更新自身状态。
- 布局调整:根据键盘和输入框的状态,IQKeyboardManager会调用adjustPosition()方法调整输入框的位置,确保输入框不被键盘遮挡。
- 状态恢复:当键盘收起或禁用键盘管理时,会调用restorePosition()方法恢复输入框的原始位置。
总结
IQKeyboardManagerSwift通过模块化的设计和巧妙的事件监听机制,实现了对iOS键盘遮挡问题的自动处理。核心类IQKeyboardManager负责统筹整个流程,IQActiveConfiguration管理当前状态,UIView+Parent等扩展类提供辅助功能。开发者可以通过简单的API调用,轻松集成这个库,解决键盘遮挡问题,提升用户体验。
官方文档:MIGRATION GUIDE 7.0 TO 8.0.md
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考





