Skip to content

Instantly share code, notes, and snippets.

@npu3pak
Last active July 2, 2018 15:44
Show Gist options
  • Save npu3pak/50f7ebf270f5a89553a47398098fb7fa to your computer and use it in GitHub Desktop.
Save npu3pak/50f7ebf270f5a89553a47398098fb7fa to your computer and use it in GitHub Desktop.
iOS. Изменение положения элементов при отображении/скрытии клавиатуры
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
let desirableBottomPadding: CGFloat = 16.0
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
bottomConstraint.constant = desirableBottomPadding
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@IBAction func onEditFinished(_ sender: UITextField) {
sender.resignFirstResponder()
}
func onKeyboardWillShow(_ notification: Notification) {
let keyboardSize = notification.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! CGRect
bottomConstraint.constant = desirableBottomPadding + keyboardSize.height
}
func onKeyboardWillHide(_ notification: Notification) {
bottomConstraint.constant = desirableBottomPadding
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment