IHKeyboardAvoiding is an elegant solution for keeping any UIView visible when the keyboard is being shown - no UIScrollView required!

Overview

IHKeyboardAvoiding

IHKeyboardAvoiding Language: Swift 4.2

An elegant solution for keeping any UIView visible when the keyboard is being shown

alt demo

Requirements

IHKeyboardAvoiding Version
Objective C 2.6.0
Swift 3.0.0 +

Description

IHKeyboardAvoiding will translate any UIView up when the keyboard is being shown, then return it when the keyboard is hidden.

Register an avoidingView(UIView) with IHKeyboardAvoiding; when the keyboard is shown, if the avoidingView's frame will be intersected by the keyboard, then it will move up just above the keyboard. When the keyboard is dismissed, the avoidingView is returned to its original position.

What sets IHKeyboardAvoiding apart from other keyboard avoiding solutions is that it doesn't require placing your content in a UIScrollView. No scroll view is used. And it isn't restricted to keeping UITextFields visible, with IHKeyboardAvoiding any UIView can avoid the keyboard

If Autolayout is used then the constraints are animated, otherwise a CGAffine translation is done.

Supported Features

  • iPhone keyboard
  • iPad docked keyboard
  • iPad undocked keyboard
  • iPad split keyboard
  • landscape & protrait
  • 3rd party keyboards
  • Auto Layout
  • AutoResizingMask (Springs & Struts)

How to install

Add this to your CocoaPods Podfile.

pod 'IHKeyboardAvoiding'

How to use

To set the avoiding view

KeyboardAvoiding.avoidingView = self.avoidingView

Put it in viewDidLoad() or viewDidAppear(_ animated: Bool) depending on your usage

If you're unsure put it in viewDidAppear(_ animated: Bool)

If you need to set the avoidingView, or its properites, dynamically consider putting it in textViewShouldBeginEditing(_ textView: UITextView)

Optional methods
KeyboardAvoiding.setAvoidingView(self.avoidingView, withTriggerView: self.triggerView) Use this to set an avoidingView but have a different view that triggers the avoiding. If a triggerView's frame will be intersected by the keyboard, then the avoidingView will be moved so that the triggerView is above the keyboard KeyboardAvoiding.buffer The avoidingView will move if the keyboard is within buffer points of the triggerView's frame. Default buffer is 0
KeyboardAvoiding.paddingForCurrentAvoidingView The padding to put between the keyboard and triggerView. Default padding is 0

Enable tap to dismiss the keyboard by simply changing any UIView to be an instance of KeyboardDismissingView in you nib/storyboard

Buy now and get this free gift :)

A Codable extension to decode arrays and to catch & log all decoding failures https://github.com/IdleHandsApps/SafeDecoder

Button styles that are centralied and reusable, and hooked up to InterfaceBuilder https://github.com/IdleHandsApps/DesignableButton

A fully automatic status bar overlay for No Internet Connection messages https://github.com/IdleHandsApps/StatusBarOverlay

IHKeyboardAvoiding vs UIScrollView solutions - Fight, fight!

UIScrollView pros:

  • They're quick n easy

IHKeyboardAvoiding pros:

  • You dont have scrollviews littered throughout your app
  • Having multiple scrollviews in your view heirarchy can cause problems
  • When the keyboard hides, scrollviews dont always scroll back to their original position
  • Scrollviews only scroll enough to keep the focused textfield visible
  • IHKeyboardAvoiding provides control over which UIViews are visible when the keyboard appears

Similar keyboard avoiding solutions

https://github.com/michaeltyson/TPKeyboardAvoiding (UIScrollView based)
https://github.com/kirpichenko/EKKeyboardAvoiding (UIScrollView based)
https://github.com/robbdimitrov/RDVKeyboardAvoiding (UIScrollView based) https://github.com/hackiftekhar/IQKeyboardManager (looks interesting) https://github.com/danielamitay/DAKeyboardControl (looks interesting)

Author

It'd be great to hear about any cool apps that are using IHKeyboardAvoiding

License

Distributed under the MIT License

Comments
  • Problem when setting one of the two TexFields to 'Secure Text Entry'

    Problem when setting one of the two TexFields to 'Secure Text Entry'

    If you are setting one of the two TextFields to "Secure Text Entry" in the Interface Builder as it is supposed for a password field, the scrolling does not work correctly any more. Didn't this bug also occur in your demo that shows the gif animation? Do you have a workaround?

    opened by s1m-0n 11
  • Regression introduced with version 1.2

    Regression introduced with version 1.2

    Hey there, I've updated my pods this morning and I've noticed a regression in the recent commit for version 1.2: the avoiding view is moved down even if the keyboard is not covering it.

    opened by nashfive 6
  • Glitch if used while on phone call

    Glitch if used while on phone call

    If you activate the keyboard while on a phone call, then disconnect the call and dismiss the keyboard, it pushes the view down further than it should go, leaving a black space at the top.

    opened by bonebox 6
  • Status bar overlapping

    Status bar overlapping

    I have the following screen, blue background being the container view and my avoiding view.

    simulator screen shot - iphone se - 2017-09-21 at 00 40 28 However, when I present my keyboard, the container view overlaps with my status bar. simulator screen shot - iphone se - 2017-09-21 at 00 40 30 Was wondering if there's any way to dodge this? My self.view.clipsToBounds is already set to true if that matters

    opened by happiehappie 5
  • Swift 3.0 setting the avoidingview to self when self is still nil crash

    Swift 3.0 setting the avoidingview to self when self is still nil crash

    Hi,

    I've updated the version of IHKeyboardAvoiding to the latest Swift version. When executing the following code: KeyboardAvoiding.avoidingView = self

    And executing this in an AwakeFromNib which isn't showing itself yet (it's a popup which will show when pressing a button) it will crash saying the following: fatal error: unexpectedly found nil while unwrapping an Optional value

    opened by TripwireNL 4
  • Change triggerFrame originInWindow calculation.

    Change triggerFrame originInWindow calculation.

    UIView that you previously created for origin calculation does not belong to any UIWindow, so this will give incorrect frame for triggerView in UIWindow coordinates.

    opened by orkenstein 4
  • keyboard avoiding not working properly on iOS 11.2

    keyboard avoiding not working properly on iOS 11.2

    Upon open the app in iOS 11.2, the keyboard avoiding is working. But only worked for once then the keyboard avoiding not working anymore. I checked with 11.1.1 , 11.1.2 , 11.2. It seems only happen at 11.2 devices. ( FYI , the issue happens when I using navigation controller and perform segue or unwind segue, after I perform one of those segues , the keyboard avoiding is not working )

    opened by aznelite89 3
  • Do it support auto layout?

    Do it support auto layout?

    It seems like IHKeyboardAvoiding doesn't support auto layout, it only moves KeyboardAvoiding.avoidingView up and down, which could potentially overlaps other views. Here's what in my storyboard screen shot 2017-06-08 at 3 57 57 pm

    each text field has same distance from its top's, the first one is in the centre of screen. If I click text field 3, it becomes like this simulator screen shot 8 jun 2017 4 00 07 pm

    Is there any way that I could achieve this? simulator screen shot 8 jun 2017 4 01 42 pm

    opened by alex-payer 3
  • Keyboard frame calculations causing issues in IOS 8

    Keyboard frame calculations causing issues in IOS 8

    The keyboard frame is also dependent on the rotation of the device in iOS 8. So this is causing the avoided view to be moved incorrectly for iOS 8 devices.

    I created my own category on UIScreen for returning the correct height or width depending on the iOS version. Maybe you could use something similar for the keyboard frame....

    + (CGFloat)screenWidth
    {
        CGFloat width = [self screenSize].width;
    
        if (![self isiOSEight])
            if ([self isLandscape])
                width = [UIScreen mainScreen].bounds.size.height;
    
        return width;
    }
    
    + (CGFloat)screenHeight
    {
        CGFloat height = [self screenSize].height;
    
        if (![self isiOSEight])
            if ([self isLandscape])
                height = [UIScreen mainScreen].bounds.size.width;
    
        return height;
    }
    
    #pragma mark - Helpers
    
    + (BOOL)isiOSEight
    {
        return ([[UIDevice currentDevice].systemVersion floatValue] < 8.0) ? NO : YES;
    }
    
    + (CGSize)screenSize
    {
        return [UIScreen mainScreen].bounds.size;
    }
    
    + (BOOL)isLandscape
    {
        return UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]);
    }
    
    opened by leewaa 3
  • AvoidingView did not update after quick type search bar is dismissed.

    AvoidingView did not update after quick type search bar is dismissed.

    Version: 4.2 Issue: The avoiding view did not update the position if the quick type search bar is dismissed. (P/S : I was implement password autofill for iOS 11 on my apps)

    opened by aznelite89 2
  • Add carthage support

    Add carthage support

    I added IHKeyboardAvoiding.xcodeproj by $swift package generate-xcodeproj and enabled carthage build. You can test the carthage build in two ways.

    • $ carthage build --no-skip-current --platform ios.
    • $ carthage update --platform ios using below Cartfile.
    github "culumn/IHKeyboardAvoiding" "feature/carthage"
    
    opened by culumn 2
  • Swift Package manager issue

    Swift Package manager issue

    Hi I am trying to use in Xcode 12.5 using SPM. I get following error. Can you please guide how i can fix this.

    Showing All Messages the manifest is missing a Swift tools version specification; consider prepending to the manifest '// swift-tools-version:5.4.0' to specify the current Swift toolchain version as the lowest Swift version supported by the project; if such a specification already exists, consider moving it to the top of the manifest, or prepending it with '//' to help Swift Package Manager find it in https://github.com/IdleHandsApps/IHKeyboardAvoiding

    opened by hassanrazakhalid 1
  • Crash _NSArrayM objectAtIndexedSubscript:]: index 0 beyond bounds for empty array

    Crash _NSArrayM objectAtIndexedSubscript:]: index 0 beyond bounds for empty array

    I have got a crash report from Fabric in the library IHKeyboardAvoiding version 2.6.0. The stack trace below:

    Fatal Exception: NSRangeException

    0  CoreFoundation                 0x1b329898c __exceptionPreprocess
    1  libobjc.A.dylib                0x1b2fc10a4 objc_exception_throw
    2  CoreFoundation                 0x1b32ee3f8 -[__NSCFString characterAtIndex:].cold.1
    3  CoreFoundation                 0x1b3182c6c -[__NSArrayM objectAtIndexedSubscript:]
    4  IHKeyboardAvoiding             0x1054f1730 +[IHKeyboardAvoiding applicationDidEnterBackground:] + 339 (IHKeyboardAvoiding.m:339)
    5  CoreFoundation                 0x1b31f409c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__
    6  CoreFoundation                 0x1b31f40e4 ___CFXRegistrationPost1_block_invoke
    7  CoreFoundation                 0x1b31f3444 _CFXRegistrationPost1
    8  CoreFoundation                 0x1b31f30fc ___CFXNotificationPost_block_invoke
    9  CoreFoundation                 0x1b316f43c -[_CFXNotificationRegistrar find:object:observer:enumerator:]
    10 CoreFoundation                 0x1b31f2a4c _CFXNotificationPost
    11 Foundation                     0x1b354f2d8 -[NSNotificationCenter postNotificationName:object:userInfo:]
    12 UIKitCore                      0x1b72abd50 __47-[UIApplication _applicationDidEnterBackground]_block_invoke
    13 UIKitCore                      0x1b6ca6da0 +[UIViewController _performWithoutDeferringTransitionsAllowingAnimation:actions:]
    14 UIKitCore                      0x1b72abb0c -[UIApplication _applicationDidEnterBackground]
    15 UIKitCore                      0x1b6a8171c __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke_2
    16 UIKitCore                      0x1b6f113ec _UIScenePerformActionsWithLifecycleActionMask
    17 UIKitCore                      0x1b6a812f8 __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke
    18 UIKitCore                      0x1b6a80d50 -[_UISceneLifecycleMultiplexer _performBlock:withApplicationOfDeactivationReasons:fromReasons:]
    19 UIKitCore                      0x1b6a81124 -[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]
    20 UIKitCore                      0x1b6a809e0 -[_UISceneLifecycleMultiplexer uiScene:transitionedFromState:withTransitionContext:]
    21 UIKitCore                      0x1b68f5610 -[UIScene _invalidate]
    22 UIKitCore                      0x1b74ceec4 -[UIWindowScene _invalidate]
    23 UIKitCore                      0x1b72a2b20 -[UIApplication workspace:willDestroyScene:withTransitionContext:completion:]
    24 UIKitCore                      0x1b6e64c10 -[UIApplicationSceneClientAgent scene:willInvalidateWithEvent:completion:]
    25 FrontBoardServices             0x1b8331bdc -[FBSSceneImpl _callOutQueue_agent_willDestroyWithTransitionContext:completion:]
    26 FrontBoardServices             0x1b8357b70 __84-[FBSWorkspaceScenesClient _queue_invalidateScene:withTransitionContext:completion:]_block_invoke_2
    27 FrontBoardServices             0x1b833c0f8 -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:]
    28 FrontBoardServices             0x1b83579e8 __84-[FBSWorkspaceScenesClient _queue_invalidateScene:withTransitionContext:completion:]_block_invoke
    29 libdispatch.dylib              0x1b2f66184 _dispatch_client_callout
    30 libdispatch.dylib              0x1b2f0f038 _dispatch_block_invoke_direct$VARIANT$mp
    31 FrontBoardServices             0x1b837b540 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__
    32 FrontBoardServices             0x1b837b20c -[FBSSerialQueue _queue_performNextIfPossible]
    33 FrontBoardServices             0x1b837b734 -[FBSSerialQueue _performNextFromRunLoopSource]
    34 CoreFoundation                 0x1b32167e0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
    35 CoreFoundation                 0x1b3216738 __CFRunLoopDoSource0
    36 CoreFoundation                 0x1b3215ed0 __CFRunLoopDoSources0
    37 CoreFoundation                 0x1b321101c __CFRunLoopRun
    38 CoreFoundation                 0x1b32108bc CFRunLoopRunSpecific
    39 GraphicsServices               0x1bd07c328 GSEventRunModal
    40 UIKitCore                      0x1b72a66d4 UIApplicationMain
    41 MyApp                           0x1050801cc main + 14 (main.m:14)
    42 libdyld.dylib                  0x1b309b460 start
    
    opened by revolutionkpi 0
  • fixes

    fixes "shake to undo" gesture bug.

    References Issue #55

    The avoidingView was not moving back to the original position after "undo typing" click.

    Basically, the problem is after the "undo typing" click the keyboardWillChangeFrameNotification observer will be called three times: 1 time: target to show the keyboard 2 time: target to hide the keyboard 3 time: target to show the keyboard

    The third call will be executed bevor the "restore state" animation from the second call is finished. Therefore in the third call, all auto location are still saved in updatedConstraints & updatedConstraintConstants. So we need to wait for the animation to finish and then call didChange with the preserved notification object.

    opened by esemusa 0
Releases(1.0.1)
Owner
Idle Hands Apps
c/- Fraser Scott-Morrison
Idle Hands Apps
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
iOS utility class allows you to access keyboard view and track keyboard animation.

YYKeyboardManager iOS utility class allows you to access keyboard view and track keyboard animation. (It was used by YYText) Compatibility iPhone / iP

null 480 Nov 17, 2022
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
For less complicated keyboard event handling.

KeyboardObserver For less complicated keyboard event handling. Features Less complicated keyboard event handling. Do not use Notification , but event

Morita Naoki 163 May 24, 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