⌨️ 键盘观察
一个适用于SwiftUI观察和避免键盘的基于Combine的解决方案。
目录
关于
此包使用Keyboard
ObservableObject
类型为您提供观察键盘状态变化的能力。
它还提供了一个KeyboardObservingView
,它将内容调整为避免键盘,以及一个.keyboardObserving()
ViewModifier,它将修改后的视图调整为避免键盘。
需求
- iOS 13.0+
- Xcode 11+
- Swift 5.1+
安装
此包可以通过CocoaPods或Swift包管理器安装。
CocoaPods
将以下行添加到您的Podfile
pod 'KeyboardObserving'
有关如何开始使用CocoaPods的更多信息,请查看CocoaPods网站。
Swift包管理器
将以下代码添加到您的Package.swift
文件中
dependencies: [
.package(
url: "https://github.com/nickffox/KeyboardObserving.git",
.branch:("master")
)
]
如果您使用Xcode通过SPM
- 转到
文件 > Swift包 > 添加包依赖
- 输入https://github.com/nickffox/KeyboardObserving
- 选择
分支
选项,并输入“master”
有关如何开始使用Swift包管理器的更多信息,请查看官方SPM网站或GitHub上的SPM项目。
用法
KeyboardObserving
ViewModifier
使用将.keyboardObserving()
ViewModifier添加到您的自定义Swift UI视图中。
import KeyboardObserving
struct YourView: View {
var body: some View {
VStack {
// Your Content Here
}
.keyboardObserving()
}
}
Keyboard
和KeyboardObservingView
使用1. 在您的环境中添加键盘
在您的 SceneDelegate.swift 文件中,添加一个 Keyboard
属性,并将其添加到您场景的环境中。
import KeyboardObserving
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
// A Keyboard that will be added to the environment.
var keyboard = Keyboard()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(
rootView: YourRootView()
// Adds the keyboard to the environment
.environmentObject(keyboard)
)
self.window = window
window.makeKeyAndVisible()
}
}
}
2. 创建您的视图
将您视图的内容添加到 KeyboardObservingView
中。
import KeyboardObserving
struct YourView: View {
var body: some View {
KeyboardObservingView {
// Your content goes here!
}
}
}