For less complicated keyboard event handling.

Overview

KeyboardObserver

For less complicated keyboard event handling.

Carthage compatible

Features

  • Less complicated keyboard event handling.
  • Do not use Notification , but event .

Difference

Without KeyboardObserver.swift

let keyboardNotifications: [Notification.Name] = [
    .UIKeyboardWillShow,
    .UIKeyboardWillHide,
    .UIKeyboardWillChangeFrame,
]

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    keyboardNotifications.forEach {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardEventNotified:), name: $0, object: nil)
    }
}

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    keyboardNotifications.forEach {
        NotificationCenter.default.removeObserver(self, name: $0, object: nil)
    }
}

@objc func keyboardEventNotified(notification: NSNotification) {
    guard let userInfo = notification.userInfo else { return }
    let keyboardFrameEnd = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let curve = UIView.AnimationCurve(rawValue: (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).intValue)!
    let options = UIView.AnimationOptions(rawValue: UInt(curve.rawValue << 16))
    let duration = TimeInterval(truncating: userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber)
    let bottom = keyboardFrameEnd.height - bottomLayoutGuide.length
    
    UIView.animate(withDuration: duration, delay: 0.0, options: [options], animations:
        { () -> Void in
            self.textView.contentInset.bottom = bottom
            self.textView.scrollIndicatorInsets.bottom = bottom
        } , completion: nil)
}

With KeyboardObserver

let keyboard = KeyboardObserver()

override func viewDidLoad() {
    super.viewDidLoad()

    keyboard.observe { [weak self] (event) -> Void in
        guard let self = self else { return }
        switch event.type {
        case .willShow, .willHide, .willChangeFrame:
            let keyboardFrameEnd = event.keyboardFrameEnd
            let bottom = keyboardFrameEnd.height - self.bottomLayoutGuide.length
            
            UIView.animate(withDuration: event.duration, delay: 0.0, options: [event.options], animations: { () -> Void in
                self.textView.contentInset.bottom = bottom
                self.textView.scrollIndicatorInsets.bottom = bottom
                }, completion: nil)
        default:
            break
        }
    }
}

How to use

Create KeyboardObserver instance where you want, and the instance observes keyboard untill deinit.

Call observe(event: KeyboardEvent) to observe keyboard events. event is converted keyboard notification object.

public struct KeyboardEvent {
    public let type: KeyboardEventType
    public let keyboardFrameBegin: CGRect
    public let keyboardFrameEnd: CGRect
    public let curve: UIViewAnimationCurve
    public let duration: NSTimeInterval
    public var isLocal: Bool?

    public var options: UIViewAnimationOptions {
        return UIViewAnimationOptions(rawValue: UInt(curve.rawValue << 16))
    }
    ...

event has properties above. You don't have to convert Notification 's userInfo to extract keyboard event values.

KeyboardEentType has types same as keyboard's notification name. Like this below:

public enum KeyboardEventType {
    case willShow
    case didShow
    case willHide
    case didHide
    case willChangeFrame
    case didChangeFrame
    ...
}

It has also public var notificationName: String which you can get original notification name.

Runtime Requirements

  • iOS 8.0 or later
  • Xcode 10.0
  • Swift4.2

Installation and Setup

Information: To use KeyboardObserver with a project targeting lower than iOS 8.0, you must include the KeyboardObserver.swift source file directly in your project.

Installing with Carthage

Just add to your Cartfile:

github "morizotter/KeyboardObserver"

Installing with CocoaPods

CocoaPods is a centralised dependency manager that automates the process of adding libraries to your Cocoa application. You can install it with the following command:

$ gem update
$ gem install cocoapods
$ pods --version

To integrate KeyboardObserver into your Xcode project using CocoaPods, specify it in your Podfile and run pod install.

platform :ios, '8.0'
use_frameworks!
pod "KeyboardObserver", '~> 2.1'

Manual Installation

To install KeyboardObserver without a dependency manager, please add KeyboardObserver.swift to your Xcode Project.

Contribution

Please file issues or submit pull requests for anything you’d like to see! We're waiting! :)

License

KeyboardObserver.swift is released under the MIT license. Go read the LICENSE file for more information.

Comments
  • Failed to push 1.0.0 to cocoapods.

    Failed to push 1.0.0 to cocoapods.

    Currently, master branch's swift verison is 3. However, I cannot succeed to push project to Cocoapods so you can not use it with Cocoapods.

    I think this relates to the cocoapods bug.

    https://github.com/CocoaPods/CocoaPods/issues/5805

    This issue was closed but the problem is maybe not solved in the 1.1.0.rc.1 release.

    I'm using

    • Xcode 8 GM
    • 1.1.0.rc.1.
    help wanted 
    opened by morizotter 6
  • keyboard.isEnabled didn't Trigger observe function

    keyboard.isEnabled didn't Trigger observe function

    I have UITextField and UIButton. I'm texing to the UItextfield and then pressing the submit button. but didn't trigger kerboard observe func.

    Share button action :

      @IBAction func shareButtonPressed(_ sender: UIButton){
        shareButton.isEnabled = false
        self.keyboard.isEnabled = !self.keyboard.isEnabled 
        }
    

    Have any solution?

    opened by emre-yilmaz 2
  • Rename enabled property into isEnabled.

    Rename enabled property into isEnabled.

    In Swift, enabled property is usually declared as isEnabled e.g. UIControl, and according to Swift API design guidelines, it says "Uses of Boolean methods and properties should read as assertions about the receiver when the use is nonmutating, e.g. x.isEmpty, line1.intersects(line2)." (You can refer to the Japanese-translated document)

    So, I post this pull request to rename the enabled property into isEnabled, but it breaks the current API. What do you think of this change?

    opened by milkcocoa 1
  • Resolve warning for Swift 2.2

    Resolve warning for Swift 2.2

    This warning occured:

    KeyboardObserver/KeyboardObserver/KeyboardObserver.swift:113:78: Use of string literal for Objective-C selectors is deprecated; use '#selector' instead
    

    This is Swift 2.2 new selector syntax, and is it okay to merge to master?

    opened by mono0926 1
  • Move `enabled` conditional expression

    Move `enabled` conditional expression

    Modify the notification settings to be switched at any time

    e.g.

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        keyboard.enabled = true
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        keyboard.enabled = false
    }
    
    opened by Econa77 1
  • Change UIAnimationOptions to UIAnimationCurve

    Change UIAnimationOptions to UIAnimationCurve

    The keyboard UINotification's curve is UIAnimationCurve. Currently it is implemented with UIAnimationOptions so fix it to correct type.

    However, it is rare to use UIAnimationCurve directly. So, I created options computed property. You can use curve easily through this property.

    And this pull request covers https://github.com/morizotter/KeyboardObserver/pull/3 .

    resolve https://github.com/morizotter/KeyboardObserver/pull/3

    opened by morizotter 0
Releases(2.1.0)
Owner
Morita Naoki
Traveller.
Morita Naoki
IHKeyboardAvoiding is an elegant solution for keeping any UIView visible when the keyboard is being shown - no UIScrollView required!

IHKeyboardAvoiding An elegant solution for keeping any UIView visible when the keyboard is being shown Requirements IHKeyboardAvoiding Version Objecti

Idle Hands Apps 1.4k Dec 14, 2022
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more.

IQKeyboardManager While developing iOS apps, we often run into issues where the iPhone keyboard slides up and covers the UITextField/UITextView. IQKey

Mohd Iftekhar Qurashi 15.9k Jan 8, 2023
Codeless manager to hide keyboard by tapping on views for iOS written in Swift

KeyboardHideManager KeyboardHideManager - codeless manager to hide keyboard by tapping on views for iOS written in Swift. Structure Features Requireme

Bondar Yaroslav 55 Oct 19, 2022
⌨️ Add user-customizable global keyboard shortcuts to your macOS app in minutes

This package lets you add support for user-customizable global keyboard shortcuts to your macOS app in minutes. It's fully sandbox and Mac App Store c

Sindre Sorhus 1.1k Dec 29, 2022
Swift UIKit keyboard manager for iOS apps.

Typist Typist is a small, drop-in Swift UIKit keyboard manager for iOS apps. It helps you manage keyboard's screen presence and behavior without notif

Toto Tvalavadze 1.1k Dec 10, 2022
Suppress mouse & keyboard events on MacOSX. Baby-proof my Mac!

Suppress mouse & keyboard events on MacOSX Catches all events (mouse, keyboard, everything), and either consumes them (locked state) or passes them th

Albert Zeyer 6 Oct 21, 2022
KeyboardKit is a Swift library that helps you create custom keyboard extensions for iOS and ipadOS.

KeyboardKit is a Swift library that helps you create custom keyboard extensions for iOS and ipadOS.

KeyboardKit 900 Jan 9, 2023
QMK Agent is a macOS menubar application which sends commands to a QMK enabled keyboard

QMKagent QMK Agent is a macOS menubar application which sends commands to a QMK enabled keyboard Features System volume indicator using top row (Esc t

Mike Killewald 4 Apr 24, 2022
Best way to dismiss Keyboard in a View Controller iOS (Swift)

Best way to dismiss Keyboard in a View Controller iOS (Swift) First way: Implement UITextFieldDelegate’s textFieldShouldReturn method and dismiss curr

null 0 Dec 18, 2021
Showing / dismissing keyboard animation in simple UIViewController category.

RSKKeyboardAnimationObserver Easy way to handle iOS keyboard showing/dismissing. Introduction Working with iOS keyboard demands a lot of duplicated co

Ruslan Skorb 45 Jun 9, 2022
Objective-C library for tracking keyboard in iOS apps.

NgKeyboardTracker Objective-c library for tracking keyboard in iOS apps. Adding to your project If you are using CocoaPods, add to your Podfile: pod '

Meiwin Fu 808 Nov 17, 2022
A simple keyboard to use with numbers and, optionally, a decimal point.

MMNumberKeyboard A simple keyboard to use with numbers and, optionally, a decimal point. Installation From CocoaPods CocoaPods is a dependency manager

Matías Martínez 957 Nov 17, 2022
A drop-in universal solution for moving text fields out of the way of the keyboard in iOS

TPKeyboardAvoiding A drop-in universal solution for moving text fields out of the way of the keyboard in iOS. Introduction There are a hundred and one

Michael Tyson 5.8k Dec 26, 2022
KeyboardMan helps you to make keyboard animation.

KeyboardMan We may need keyboard infomation from keyboard notifications to do animation. However, the approach is complicated and easy to make mistake

null 353 Apr 19, 2022
Emoji Keyboard SDK (iOS)

Makemoji SDK Makemoji is a free emoji keyboard for mobile apps. By installing our keyboard SDK every user of your app will instantly have access to ne

Makemoji 100 Nov 3, 2022
A Chinese keyboard for iOS that helps Chinese language learners remember tones.

ToneBoard ToneBoard is a Chinese keyboard for iOS that requires you to enter the correct tones while typing simplified Chinese with Pinyin. It is avai

Kevin Bell 7 Sep 27, 2022
SwiftyKeyboard: a full customized numeric keyboard for iOS

SwiftyKeyboard Overview SwiftyKeyboard is an iOS customized enhanced keyboard. T

SwiftyKit 2 Jun 30, 2022
Interactive Keyboard Controller for Swift

Keynode Why Using UIScrollViewKeyboardDismissMode added in iOS7, interactive keyboard operation became possible. But, it only works on UIScrollView. K

Kyohei Ito 76 Sep 1, 2020
⌨️A Combine-based way to observe and adjust for Keyboard notifications in SwiftUI

⌨️ Keyboard Observing A Combine-based solution for observing and avoiding the keyboard in SwiftUI. Table of Contents About Requirements Installation C

Nick Fox 440 Jan 5, 2023