SwiftUI解决隐藏NavigationBar后返回失效

SwiftUI解决隐藏NavigationBar后返回失效

获取小键盘高度

@ObservedObject private var keyboard = KeyboardResponder()
keyboard.currentHeight

通过小键盘高度判断是否需要添加灰色背景,点击灰色背景隐藏小键盘
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if keyboard.currentHeight != 0 {
Color.gray
.edgesIgnoringSafeArea(.all)
.opacity(0.4)
.onTapGesture {
withAnimation(.spring()){
UIApplication.shared.windows.forEach { (window) in
if window.isKeyWindow {
window.endEditing(true)
}
}
}
}
}

效果图

keyboardhandle.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import UIKit
import Foundation
import SwiftUI
import Combine
class KeyboardResponder: ObservableObject {
private var _center: NotificationCenter
@Published var currentHeight: CGFloat = 0

init(center: NotificationCenter = .default) {
_center = center
_center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
_center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}

deinit {
_center.removeObserver(self)
}

@objc func keyBoardWillShow(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
currentHeight = keyboardSize.height
}
}

@objc func keyBoardWillHide(notification: Notification) {
currentHeight = 0
}
}

class KeyboardHeightHelper: ObservableObject {
@Published var keyboardHeight: CGFloat = 0

init() {
self.listenForKeyboardNotifications()
}
private func listenForKeyboardNotifications() {
NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification,
object: nil,
queue: .main) { (notification) in
guard let userInfo = notification.userInfo,
let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
self.keyboardHeight = keyboardRect.height
}

NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidHideNotification,
object: nil,
queue: .main) { (notification) in
self.keyboardHeight = 0
}
}
}
发布于

2021-06-09

更新于

2021-06-15

许可协议

评论

:D 一言句子获取中...

加载中,最新评论有1分钟缓存...