Skip to content

Instantly share code, notes, and snippets.

@dobaduc
Last active October 5, 2015 02:09
Show Gist options
  • Save dobaduc/f14f4e2edd0b751898f5 to your computer and use it in GitHub Desktop.
Save dobaduc/f14f4e2edd0b751898f5 to your computer and use it in GitHub Desktop.
Automatically adjust scroll view according to keyboard visibility
//
// AutoKeyboardAdjustmentProtocol.swift
// Ducky Duke
//
// Created by Doba Duc on 8/18/15.
// Copyright (c) 2015 Doba Duc. All rights reserved.
//
import UIKit
public protocol AutoKeyboardAdjustmentProtocol {
var scrollViewForKeyboardAdjustment: UIScrollView? { get }
func contentInset(forKeyboardHeight keyboardHeight: CGFloat) -> UIEdgeInsets
func adjustContent(keyboardHeight keyboardHeight: CGFloat)
}
extension UIViewController: AutoKeyboardAdjustmentProtocol {
public var scrollViewForKeyboardAdjustment: UIScrollView? {
return nil
}
// Call this to enable auto adjustment. E.g.: In `viewDidLoad()`
public func enableKeyboardAutoHandling() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
// Call this to enable auto adjustment. E.g.: In `deinit`
public func disableKeyboardAutoHandling() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
public func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]!.CGRectValue {
adjustContent(keyboardHeight: keyboardSize.height)
}
}
public func keyboardWillHide(notification: NSNotification) {
adjustContent(keyboardHeight: 0)
}
public func contentInset(forKeyboardHeight keyboardHeight: CGFloat) -> UIEdgeInsets {
if let scrollView = scrollViewForKeyboardAdjustment {
return UIEdgeInsets(top: scrollView.contentInset.top, left: scrollView.contentInset.left, bottom: keyboardHeight, right: scrollView.contentInset.right)
} else {
return UIEdgeInsetsZero
}
}
public func adjustContent(keyboardHeight keyboardHeight: CGFloat) {
guard let scrollView = scrollViewForKeyboardAdjustment else { return }
UIView.animateWithDuration(0.3,
delay: 0,
options: .CurveEaseOut,
animations: {
scrollView.contentInset = self.contentInset(forKeyboardHeight: keyboardHeight)
},
completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment