Skip to content

Instantly share code, notes, and snippets.

@fitomad
Created November 23, 2019 15:39
Show Gist options
  • Save fitomad/0e593b6be8e69955272821007469955a to your computer and use it in GitHub Desktop.
Save fitomad/0e593b6be8e69955272821007469955a to your computer and use it in GitHub Desktop.
//
// KeyboardResponder.swift
// MoveMAD
//
// Created by Adolfo Vera Blasco on 19/11/2019.
// Copyright © 2019 desappstre {eStudio}. All rights reserved.
//
import Combine
import SwiftUI
public final class KeyboardResponder: ObservableObject
{
/// Altura del teclado en un momento dado
@Published public private(set) var currentHeight: CGFloat = 0.0
/// Duración de la animación del sistema que presenta el teclado
@Published public private(set) var animationDuration: Double = 0.0
/**
Nos *enganchamos* a las notificaciones
de presentación del teclado.
*/
public init()
{
// Notificación para cuando se presenta el teclado
NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
.receive(on: RunLoop.main)
.tryMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect }
.replaceError(with: CGRect.zero)
.map { $0.height }
.sink () { newHeight in
self.currentHeight = newHeight
}
// Notificación cuando se va a ocultar el teclado
NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)
.receive(on: RunLoop.main)
.tryMap { $0.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double }
.replaceError(with: 0.35)
.sink () { animationDuration in
self.currentHeight = 0.0
self.animationDuration = animationDuration
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment