redribben icon

keyboard control

redribben | PRO | 12/12/17 06:28:11 AM UTC | 0 ⭐ | 409 👁️ | Never ⏰ | []
Swift |

2.2 KB

|

None

|

0 👍

/

0 👎

override func viewDidLoad() {
//...
NotificationCenter.default.addObserver( self, selector: #selector(resizeSectionIndex), name: NSNotification.Name.UIKeyboardWillShow, object: nil )
        NotificationCenter.default.addObserver( self, selector: #selector(resizeSectionIndex), name: NSNotification.Name.UIKeyboardWillHide, object: nil )
//...
}
 
 
    @objc func resizeSectionIndex(_ notification: Notification) {
        if UIDevice().userInterfaceIdiom == .phone {
            switch UIScreen.main.nativeBounds.height {
            case 1136:
                print("iPhone 5 or 5S or 5C")
            case 1334:
                print("iPhone 6/6S/7/8")
            case 2208:
                print("iPhone 6+/6S+/7+/8+")
            case 2436:
                print("iPhone X")
                return
            default:
                print("unknown")
            }
        }
        let keyboardHeightInitial = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.height
        let keyboardHeightFinal = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height
        
//        print("Initial height: \(keyboardHeightInitial)")
//        print("Final height: \(keyboardHeightFinal)")
        
        if notification.name == .UIKeyboardWillHide {
            if keyboardHeightInitial != 0 && keyboardHeightInitial != keyboardHeightFinal {
                let keyboardHeightDifference = keyboardHeightFinal! - keyboardHeightInitial!
                tableView.frame.size.height = tableView.frame.size.height + keyboardHeightDifference
                return
            }
            tableView.frame.size.height = tableView.frame.size.height + keyboardHeightFinal!
        }
        
        if notification.name == .UIKeyboardWillShow {
            if keyboardHeightInitial != keyboardHeightFinal {
                let keyboardHeightDifference = keyboardHeightFinal! - keyboardHeightInitial!
                tableView.frame.size.height = tableView.frame.size.height - keyboardHeightDifference
                return
            }
            tableView.frame.size.height = tableView.frame.size.height - keyboardHeightFinal!
        }
    }

Comments