阅读视图

发现新文章,点击刷新页面。

键盘管理IQKeyboardManagerSwift全解

简要:

  • IQKeyboardManagerSwift:自动管理键盘,防止覆盖输入框,无需代码,适合快速集成。
  • IQKeyboardCore:提供辅助功能,非独立使用,包含视图扩展和协议。
  • IQKeyboardNotification:轻量级键盘事件监听,易于订阅键盘变化。
  • IQKeyboardReturnManager:管理回车键,方便导航到下一个输入框。
  • IQKeyboardToolbar:自定义键盘工具栏,支持上一页、下一页和完成按钮。
  • IQKeyboardToolbarManager:全局管理工具栏,统一应用设置。
  • IQTextInputViewNotification:监听输入框事件,如聚焦和失焦。
  • IQTextView:支持占位符的文本视图,增强用户体验。

1. IQKeyboardManagerSwift

  • 概述
    IQKeyboardManagerSwift 是一个无需代码的通用库,防止键盘覆盖 UITextFieldUITextView,自动管理键盘行为。

  • 主要功能

    • 自动调整键盘与输入框的距离,无需 UIScrollView 或子类化。
    • 支持所有方向,包含工具栏(Previous、Next、Done 按钮)。
    • 可定制化:调整键盘与输入框的距离、工具栏按钮行为、导航音效等。
    • 不需要手动导入,集成简单。
  • 主要属性和方法

    • shared: 返回单例实例。
    • isEnabled: 启用或禁用管理器(Bool)。
    • keyboardDistanceFromTextField: 设置键盘与输入框的距离(默认 10,单位像素)。
    • preventShowingBottomBlankSpace: 防止键盘滑动时显示底部空白区域(默认 YES)。
    • enableAutoToolbar: 启用自动工具栏(默认 YES)。
    • toolbarManageBehaviour: 设置工具栏管理行为(IQAutoToolbarBySubviews 或 IQAutoToolbarByTag)。
    • shouldResignOnTouchOutside: 触摸外部时隐藏键盘(Bool)。
    • resignFirstResponder(): 使当前第一响应者失焦。
    • canGoPrevious, canGoNext: 检查是否能导航到前一或后一输入框(只读)。
    • goPrevious(), goNext(): 导航到前一或后一输入框(返回 Bool)。
  • 安装

    • CocoaPods: pod 'IQKeyboardManagerSwift' 或特定版本如 pod 'IQKeyboardManagerSwift', '8.0.0'
    • Carthage: 添加 github "hackiftekhar/IQKeyboardManager" 到 Cartfile,运行 carthage update --use-xcframeworks,包含 IQKeyboardManagerSwift.xcframework
    • SPM: 通过 Xcode 安装。
  • 使用示例

    import IQKeyboardManagerSwift
    
    @main
    class AppDelegate: UIResponder, UIApplicationDelegate {
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            IQKeyboardManager.shared.isEnabled = true
            IQKeyboardManager.shared.keyboardDistanceFromTextField = 20
            return true
        }
    }
    
    • 注解:启用管理器并设置键盘与输入框的距离为 20 像素。
  • 注意事项

    • 不建议作为第三方库依赖,可能与其他库冲突,需在呈现/隐藏第三方 UI 时启用/禁用。
    • 版本 7.2.0 引入子模块(如 Appearance、IQKeyboardReturnManager 等),8.0.0 移除已废弃类。

2. IQKeyboardCore

  • 概述
    IQKeyboardCore 提供 IQKeyboard 相关库的公共函数和扩展,不独立使用,包含 IQTextInputView 协议和 UIView 扩展。

  • 主要功能

    • IQTextInputView 协议:由 UITextFieldUITextViewUISearchBar 采纳。
    • IQEnableMode 枚举:支持默认、启用、禁用模式。
    • UIView 扩展:提供 viewContainingController()superviewOf(type:belowView:) 等方法。
  • 主要方法

    • viewContainingController(): 获取包含当前视图的控制器。
    • superviewOf(type:belowView:): 查找指定类型的父视图。
    • textFieldSearchBar(): 检查是否为文本字段或搜索栏。
    • isAlertViewTextField(): 检查是否为警告视图的文本字段。
  • 使用示例

    import IQKeyboardCore
    
    let controller = view.iq.viewContainingController()
    let scrollView = view.iq.superviewOf(type: UIScrollView.self)
    
    • 注解:获取当前视图的控制器和父滚动视图。

3. IQKeyboardNotification

  • 概述
    IQKeyboardNotification 是一个轻量级库,方便订阅键盘事件,获取键盘框架变化。

  • 主要功能

    • 通过唯一标识符订阅键盘事件。
    • 提供键盘事件和框架信息。
  • 主要方法

    • init(): 初始化通知实例。
    • subscribe(identifier:action:): 订阅键盘事件,闭包接收事件和框架。
    • unsubscribe(identifier:): 取消订阅。
  • 使用示例

    import IQKeyboardNotification
    
    private let keyboard: IQKeyboardNotification = .init()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        keyboard.subscribe(identifier: "myID") { event, frame in
            print("Keyboard event: \(event), frame: \(frame)")
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        keyboard.unsubscribe(identifier: "myID")
    }
    
    • 注解:在视图出现时订阅键盘事件,消失时取消订阅。

4. IQKeyboardReturnManager

  • 概述
    IQKeyboardReturnManager 管理回车键行为,支持导航到下一个响应者或隐藏键盘。

  • 主要功能

    • 自动处理回车键导航。
    • 自定义回车键类型(如 Done)。
  • 主要方法

    • init(): 初始化管理器。
    • addResponderSubviews(of:recursive:): 添加响应者子视图,递归处理。
    • dismissTextViewOnReturn: 设置是否在回车时隐藏文本视图(Bool)。
    • lastTextInputViewReturnKeyType: 设置最后一个输入视图的回车键类型。
  • 使用示例

    import IQKeyboardReturnManager
    
    let returnManager: IQKeyboardReturnManager = .init()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        returnManager.addResponderSubviews(of: self.view, recursive: true)
        returnManager.dismissTextViewOnReturn = true
        returnManager.lastTextInputViewReturnKeyType = .done
    }
    
    • 注解:启用回车键导航,设置隐藏文本视图和最后回车键为 Done。

5. IQKeyboardToolbar

  • 概述
    IQKeyboardToolbar 提供自定义键盘工具栏功能,支持添加 Previous、Next、Done 按钮。

  • 主要功能

    • 添加工具栏按钮,如 Previous、Next、Done。
    • 自定义按钮标题或图片,添加额外按钮。
  • 主要方法

    • addPreviousNextDone(target:previousAction:nextAction:doneAction:showPlaceholder:): 添加 Previous、Next、Done 按钮。
    • addPreviousNextRight(target:previousConfiguration:nextConfiguration:rightConfiguration:title:): 添加自定义按钮。
    • addDone(target:action:title:): 添加 Done 按钮。
    • hidePlaceholder: 隐藏占位符(Bool)。
    • placeholder: 设置自定义占位符。
  • 使用示例

    import IQKeyboardToolbar
    
    textField.iq.addPreviousNextDone(target: self, previousAction: #selector(previousAction), nextAction: #selector(nextAction), doneAction: #selector(doneAction), showPlaceholder: true)
    
    • 注解:为文本字段添加 Previous、Next 和 Done 按钮,显示占位符。

6. IQKeyboardToolbarManager

  • 概述
    IQKeyboardToolbarManager 全局管理键盘工具栏,提供统一设置。

  • 主要功能

    • 启用和定制工具栏,检查导航能力。
  • 主要方法

    • isEnabled: 启用或禁用管理器(Bool)。
    • toolbarConfiguration: 定制工具栏外观(如 tintColor、barTintColor)。
    • canGoPrevious, canGoNext: 检查是否能导航(只读)。
    • goPrevious(), goNext(): 导航到前一或后一输入框。
  • 使用示例

    import IQKeyboardToolbarManager
    
    IQKeyboardToolbarManager.shared.isEnabled = true
    IQKeyboardToolbarManager.shared.toolbarConfiguration.tintColor = .blue
    
    • 注解:启用工具栏管理器,设置工具栏颜色为蓝色。

7. IQTextInputViewNotification

  • 概述
    IQTextInputViewNotification 方便订阅 UITextField/UITextView 的聚焦和失焦事件。

  • 主要功能

    • 订阅输入框事件,获取事件和输入视图信息。
  • 主要方法

    • init(): 初始化通知实例。
    • subscribe(identifier:action:): 订阅事件,闭包接收事件信息。
    • unsubscribe(identifier:): 取消订阅。
  • 使用示例

    import IQTextInputViewNotification
    
    private let textInputViewObserver: IQTextInputViewNotification = .init()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textInputViewObserver.subscribe(identifier: "myID") { info in
            print("Event: \(info.event.name), TextInputView: \(info.textInputView)")
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textInputViewObserver.unsubscribe(identifier: "myID")
    }
    
    • 注解:订阅输入框事件,打印事件名称和相关视图。

8. IQTextView

  • 概述
    IQTextView 是 UITextView 的子类,支持占位符功能。

  • 主要功能

    • 设置占位符文本和颜色,兼容 IQKeyboardToolbarManager。
  • 主要方法

    • placeholder: 设置占位符文本。
    • placeholderTextColor: 设置占位符颜色。
  • 使用示例

    import IQTextView
    
    let textView = IQTextView()
    textView.placeholder = "Enter your message here..."
    textView.placeholderTextColor = .lightGray
    
    • 注解:创建支持占位符的文本视图,设置占位符和颜色。

功能与方法总结表

以下是各库的主要功能和方法汇总:

库名 主要功能 主要方法
IQKeyboardManagerSwift 自动键盘管理,工具栏定制 isEnabled, keyboardDistanceFromTextField, goNext()
IQKeyboardCore 辅助功能,视图扩展 viewContainingController(), superviewOf(type:)
IQKeyboardNotification 键盘事件订阅 subscribe(identifier:action:), unsubscribe(identifier:)
IQKeyboardReturnManager 回车键导航管理 addResponderSubviews(of:recursive:), dismissTextViewOnReturn
IQKeyboardToolbar 自定义键盘工具栏 addPreviousNextDone(target:previousAction:nextAction:doneAction:), hidePlaceholder
IQKeyboardToolbarManager 全局工具栏管理 isEnabled, toolbarConfiguration, canGoPrevious
IQTextInputViewNotification 输入框事件监听 subscribe(identifier:action:), unsubscribe(identifier:)
IQTextView 支持占位符的文本视图 placeholder, placeholderTextColor

Kingfisher图像处理库

Kingfisher 是一个功能强大的 Swift 图像处理库,专注于从网络加载、缓存和显示图像,广泛用于 iOS 开发。其 GitHub 仓库提供了丰富的文档和示例,方便开发者快速集成和使用。

方法和功能分类

Kingfisher 的方法主要通过扩展现有 UIKit 和 SwiftUI 组件实现,提供了便捷的链式调用和回调机制。以下按功能分类整理:

1. 基本图像加载
  • 方法: imageView.kf.setImage(with: url)
  • 描述: 将图像从 URL 异步下载并设置到 UIImageView,支持占位符、处理器、过渡动画和完成回调。
  • 代码示例:
    let url = URL(string: "https://example.com/image.png")
    imageView.kf.setImage(with: url, placeholder: UIImage(named: "placeholder"), options: [.transition(.fade(0.25))], completionHandler: { result in
        switch result {
        case .success(let value):
            print("Image loaded: \(value.image)")
        case .failure(let error):
            print("Error: \(error)")
        }
    })
    
  • 注解: 这是最常用的方法,支持多种选项配置,适合简单场景。
2. 方法链式调用(KF.url)
  • 方法: KF.url(url)
  • 描述: 通过方法链式调用配置图像加载选项,然后应用到目标视图(如 UIImageView),提供更灵活的控制。
  • 代码示例:
    KF.url(URL(string: "https://example.com/image.png"))
      .placeholder(UIImage(named: "placeholder"))
      .setProcessor(DownsamplingImageProcessor(size: imageView.bounds.size))
      .transition(.fade(1))
      .cacheOriginalImage()
      .onProgress { receivedSize, totalSize in
          print("\(receivedSize)/\(totalSize)")
      }
      .onSuccess { result in
          print("Success: \(result.image)")
      }
      .onFailure { error in
          print("Error: \(error)")
      }
      .set(to: imageView)
    
  • 注解: 支持占位符、图像处理器、过渡动画、缓存策略、进度和完成回调,适合复杂场景。
3. SwiftUI 支持(KFImage)
  • 方法: KFImage.url(url)
  • 描述: 在 SwiftUI 中加载和显示图像,支持链式调用配置,类似于 KF.url
  • 代码示例:
    KFImage(URL(string: "https://example.com/image.png"))
      .placeholder {
        Image("placeholder")
      }
      .resizable()
      .scaledToFit()
      .onProgress { receivedSize, totalSize in
          print("\(receivedSize)/\(totalSize)")
      }
      .onSuccess { result in
          print("Success: \(result.image)")
      }
      .onFailure { error in
          print("Error: \(error)")
      }
    
  • 注解: 适用于 SwiftUI 项目,提供类似的功能和配置选项。
4. 图像处理器
  • 方法: .setProcessor(processor)
  • 描述: 应用图像处理器,例如缩放、圆角等,内置多种处理器如 DownsamplingImageProcessorRoundCornerImageProcessor
  • 代码示例:
    let processor = RoundCornerImageProcessor(cornerRadius: 20)
    imageView.kf.setImage(with: URL(string: "https://example.com/image.png"), options: [.processor(processor)])
    
  • 注解: 适合对图像进行预处理,如调整大小或添加圆角。
5. 缓存管理
  • 方法: KingfisherManager.shared.cache
  • 描述: 访问和管理 Kingfisher 的缓存系统,包括内存缓存和磁盘缓存,支持清理、检查状态等。
  • 代码示例:
    let cache = KingfisherManager.shared.cache
    cache.clearDiskCache()
    cache.calculateDiskCacheSize { size in
        print("Disk cache size: \(size) bytes")
    }
    
  • 注解: 提供细粒度的缓存控制,适合优化性能。
6. 预加载图像
  • 方法: ImagePrefetcher(urls: [url])
  • 描述: 预加载一组图像以提升加载速度,适合在应用启动时或预期需要时使用。
  • 代码示例:
    let urls = [URL(string: "https://example.com/image1.png"), URL(string: "https://example.com/image2.png")]
    ImagePrefetcher(urls: urls).start()
    
  • 注解: 提高用户体验,减少首次加载延迟。
7. 其他 UI 组件扩展
  • 方法: button.kf.setImage(with: url, for: .normal)
  • 描述: 为其他 UI 组件(如 UIButtonNSButton)提供图像加载扩展。
  • 代码示例:
    button.kf.setImage(with: URL(string: "https://example.com/image.png"), for: .normal)
    
  • 注解: Kingfisher 支持多种 UI 组件的扩展,增强灵活性。
8. 过渡动画
  • 方法: .transition(.fade(duration))
  • 描述: 设置图像加载完成时的过渡动画,支持多种效果如淡入、缩放。
  • 代码示例:
    imageView.kf.setImage(with: URL(string: "https://example.com/image.png"), options: [.transition(.fade(1))])
    
  • 注解: 提升视觉效果,适合用户界面优化。
9. 占位符和指示器
  • 方法: .placeholder(image)
  • 描述: 在图像加载过程中显示占位符或指示器,支持自定义图像或系统指示器。
  • 代码示例:
    imageView.kf.setImage(with: URL(string: "https://example.com/image.png"), placeholder: UIImage(named: "placeholder"))
    
  • 注解: 提供加载过程中的用户反馈,增强体验。
10. 低数据模式支持
  • 方法: .lowDataModeSource(.network(lowResolutionURL))
  • 描述: 在低数据模式下,使用低分辨率图像,优化流量和性能。
  • 代码示例:
    KF.url(URL(string: "https://example.com/image.png"))
      .lowDataModeSource(.network(URL(string: "https://example.com/low-res.png")))
      .set(to: imageView)
    
  • 注解: 适合移动设备在低数据模式下的优化。
11. 进度和完成回调
  • 方法: .onProgress.onSuccess.onFailure
  • 描述: 分别用于监控下载进度、处理成功和失败情况,提供对下载过程的全面控制。
  • 代码示例:
    KF.url(URL(string: "https://example.com/image.png"))
      .onProgress { receivedSize, totalSize in
          print("\(receivedSize)/\(totalSize)")
      }
      .onSuccess { result in
          print("Success: \(result.image)")
      }
      .onFailure { error in
          print("Error: \(error)")
      }
      .set(to: imageView)
    
  • 注解: 适合需要实时反馈的场景,如进度条显示。
12. Live Photo 支持
  • 方法: .loadLivePhoto
  • 描述: 加载和缓存 Live Photo,适用于支持 Live Photo 的场景。
  • 代码示例:
    imageView.kf.setImage(with: URL(string: "https://example.com/livephoto"), options: [.loadLivePhoto], completionHandler: nil)
    
  • 注解: 扩展了 Kingfisher 的功能,适合动态图像场景。

方法总结表

以下表格汇总了所有方法及其主要功能,便于快速查阅:

方法 主要功能
imageView.kf.setImage 基本图像加载,支持占位符和动画
KF.url 方法链式调用,灵活配置加载选项
KFImage.url SwiftUI 支持,加载和显示图像
.setProcessor 应用图像处理器,如缩放、圆角
KingfisherManager.shared.cache 管理缓存,清理和检查状态
ImagePrefetcher 预加载图像,提升加载速度
button.kf.setImage 扩展支持其他 UI 组件
.transition 设置加载完成时的过渡动画
.placeholder 设置加载过程中的占位符
.lowDataModeSource 低数据模式下使用低分辨率图像
.onProgress 监控下载进度
.onSuccess 处理加载成功
.onFailure 处理加载失败
.loadLivePhoto 加载和缓存 Live Photo

其他重要功能

  • 异步下载和缓存: Kingfisher 支持高效的异步下载和多级缓存(内存和磁盘),提升性能。
  • 自定义处理器: 用户可以扩展 Kingfisher 添加自定义图像处理器,满足特定需求。
  • 独立组件: 下载器、缓存系统和处理器可以独立使用,灵活性高。
  • SwiftUI 兼容性: 通过 KFImage 支持 SwiftUI,确保现代化开发支持。
  • Swift 6 和 Swift Concurrency 支持: 确保未来兼容性,适合长期项目。

FB 最新版本SDK事件上传

引言 FBSDKAppEvents 是 Facebook SDK for iOS 中的核心组件,旨在帮助开发者记录应用内事件(如用户行为、购买、推送通知互动等),用于分析和广告优化(如动态广告、转化追
❌