forked from haaakon/SingleLineKeyboardResize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UIViewController+Keyboard.swift
58 lines (50 loc) · 2.9 KB
/
UIViewController+Keyboard.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
// UIViewController+Keyboard.swift
//
// Created by Håkon Bogen on 10/12/14.
// Copyright (c) 2014 Håkon Bogen. All rights reserved.
// MIT LICENSE
import UIKit
private var scrollViewKey : UInt8 = 0
extension UIViewController {
public func setupKeyboardNotifcationListenerForScrollView(scrollView: UIScrollView) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UIViewController.keyboardWillShow(_:)), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UIViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
internalScrollView = scrollView
}
public func removeKeyboardNotificationListeners() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
private var internalScrollView: UIScrollView! {
get {
return objc_getAssociatedObject(self, &scrollViewKey) as? UIScrollView
}
set(newValue) {
objc_setAssociatedObject(self, &scrollViewKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
func keyboardWillShow(notification: NSNotification) {
let userInfo = notification.userInfo as! Dictionary<String, AnyObject>
let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
let keyboardFrameConvertedToViewFrame = view.convertRect(keyboardFrame!, fromView: nil)
let options = UIViewAnimationOptions.BeginFromCurrentState
UIView.animateWithDuration(animationDuration, delay: 0, options:options, animations: { () -> Void in
let insetHeight = (self.internalScrollView.frame.height + self.internalScrollView.frame.origin.y) - keyboardFrameConvertedToViewFrame.origin.y
self.internalScrollView.contentInset = UIEdgeInsetsMake(0, 0, insetHeight, 0)
self.internalScrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, insetHeight, 0)
}) { (complete) -> Void in
}
}
func keyboardWillHide(notification: NSNotification) {
let userInfo = notification.userInfo as! Dictionary<String, AnyObject>
let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
let options = UIViewAnimationOptions.BeginFromCurrentState
UIView.animateWithDuration(animationDuration, delay: 0, options:options, animations: { () -> Void in
self.internalScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
self.internalScrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, 0)
}) { (complete) -> Void in
}
}
}