Created
April 26, 2020 11:50
-
-
Save wmhass/e09a991bbb2bf958f4da6ed37242e395 to your computer and use it in GitHub Desktop.
SwiftUI Wrapper to Avoid Keyboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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