Get the frame of the keyboard dynamically

前端 未结 4 1168
逝去的感伤
逝去的感伤 2020-12-14 00:48

Is it possible to get the frame, actually its height, of the keyboard dynamically? As I have a UITextView and I would like to adjust its height according to the

4条回答
  •  悲&欢浪女
    2020-12-14 01:08

    For the Swift 3 users, the @Hector code (with some additions) would be:

    In your viewDidLoad add the observer :

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: .UIKeyboardDidShow , object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: .UIKeyboardDidHide , object: nil)
    

    Then implement those methods:

    func keyboardDidShow(_ notification: NSNotification) {
         print("Keyboard will show!")
         // print(notification.userInfo)
    
         let keyboardSize:CGSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size
         print("Keyboard size: \(keyboardSize)")  
    
         let height = min(keyboardSize.height, keyboardSize.width)
         let width = max(keyboardSize.height, keyboardSize.width)
    
    }
    
    func keyboardDidHide(_ notification: NSNotification) {
            print("Keyboard will hide!")
    }
    

提交回复
热议问题