redribben

keyboard control

Dec 12th, 2017
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.20 KB | None | 0 0
  1. override func viewDidLoad() {
  2. //...
  3. NotificationCenter.default.addObserver( self, selector: #selector(resizeSectionIndex), name: NSNotification.Name.UIKeyboardWillShow, object: nil )
  4.         NotificationCenter.default.addObserver( self, selector: #selector(resizeSectionIndex), name: NSNotification.Name.UIKeyboardWillHide, object: nil )
  5. //...
  6. }
  7.  
  8.  
  9.     @objc func resizeSectionIndex(_ notification: Notification) {
  10.         if UIDevice().userInterfaceIdiom == .phone {
  11.             switch UIScreen.main.nativeBounds.height {
  12.             case 1136:
  13.                 print("iPhone 5 or 5S or 5C")
  14.             case 1334:
  15.                 print("iPhone 6/6S/7/8")
  16.             case 2208:
  17.                 print("iPhone 6+/6S+/7+/8+")
  18.             case 2436:
  19.                 print("iPhone X")
  20.                 return
  21.             default:
  22.                 print("unknown")
  23.             }
  24.         }
  25.         let keyboardHeightInitial = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.height
  26.         let keyboardHeightFinal = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height
  27.        
  28. //        print("Initial height: \(keyboardHeightInitial)")
  29. //        print("Final height: \(keyboardHeightFinal)")
  30.        
  31.         if notification.name == .UIKeyboardWillHide {
  32.             if keyboardHeightInitial != 0 && keyboardHeightInitial != keyboardHeightFinal {
  33.                 let keyboardHeightDifference = keyboardHeightFinal! - keyboardHeightInitial!
  34.                 tableView.frame.size.height = tableView.frame.size.height + keyboardHeightDifference
  35.                 return
  36.             }
  37.             tableView.frame.size.height = tableView.frame.size.height + keyboardHeightFinal!
  38.         }
  39.        
  40.         if notification.name == .UIKeyboardWillShow {
  41.             if keyboardHeightInitial != keyboardHeightFinal {
  42.                 let keyboardHeightDifference = keyboardHeightFinal! - keyboardHeightInitial!
  43.                 tableView.frame.size.height = tableView.frame.size.height - keyboardHeightDifference
  44.                 return
  45.             }
  46.             tableView.frame.size.height = tableView.frame.size.height - keyboardHeightFinal!
  47.         }
  48.     }
Advertisement
Add Comment
Please, Sign In to add comment