Skip to content

Instantly share code, notes, and snippets.

@wmhass
Created April 26, 2020 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wmhass/e09a991bbb2bf958f4da6ed37242e395 to your computer and use it in GitHub Desktop.
Save wmhass/e09a991bbb2bf958f4da6ed37242e395 to your computer and use it in GitHub Desktop.
SwiftUI Wrapper to Avoid Keyboard
//
// AvoidKeyboard.swift
// TPLinkRouterMonitoriOSApp
//
// Created by William Hass on 2020-04-26.
// Copyright © 2020 William. All rights reserved.
//
import SwiftUI
import Combine
struct AvoidKeyboard<Content>: View where Content : View {
private let content: Content
@State private var keyboardHeight: CGFloat = 0
init(content: Content) {
self.content = content
}
var body: some View {
content
.padding(.bottom, keyboardHeight)
.onReceive(Publishers.keyboardHeight) { self.keyboardHeight = $0 }
}
}
extension Publishers {
static var keyboardHeight: AnyPublisher<CGFloat, Never> {
let willShow = NotificationCenter.default.publisher(for: UIApplication.keyboardWillShowNotification)
.map { $0.keyboardHeight }
let willHide = NotificationCenter.default.publisher(for: UIApplication.keyboardWillHideNotification)
.map { _ in CGFloat(0) }
return MergeMany(willShow, willHide)
.eraseToAnyPublisher()
}
}
extension Notification {
var keyboardHeight: CGFloat {
return (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect)?.height ?? 0
}
}
extension View {
func avoidKeyboard() -> some View {
AvoidKeyboard(content: self)
}
}
// Usage:
// List { }.avoidKeyboard()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment