Guest User

Untitled

a guest
Nov 19th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. override func viewDidLoad() {
  2. super.viewDidLoad()
  3.  
  4. // 註冊監控
  5. NotificationCenter.default.addObserver(
  6. self,
  7. selector: #selector(keyboardWillShow), // 執行keyboardWillShow function
  8. name: NSNotification.Name.UIKeyboardWillShow, // 在鍵盤跳出來的時候
  9. object: nil
  10. )
  11. NotificationCenter.default.addObserver(
  12. self,
  13. selector: #selector(keyboardWillHide), // 執行keyboardWillHide function
  14. name: NSNotification.Name.UIKeyboardWillHide, // 在鍵盤收起來的時候
  15. object: nil
  16. )
  17. }
  18.  
  19. @objc func keyboardWillShow(_ notification: Notification) {
  20. // 擷取鍵盤高度,並將view的y座標設定為負的鍵盤高度,這樣view就會往上提高
  21. if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
  22. let keyboardRectangle = keyboardFrame.cgRectValue
  23. keyboardHeight = keyboardRectangle.height
  24. self.view.frame = CGRect(x: 0.0, y: -keyboardHeight, width: self.view.frame.width, height: self.view.frame.size.height)
  25. }
  26. }
  27. @objc func keyboardWillHide(_ notification: Notification) {
  28. // 鍵盤收起來時,就將view歸回原位
  29. self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
  30. }
Add Comment
Please, Sign In to add comment