4

I have an textview at bottom of screen and search bar at top of screen. Following is my code to solve the problem of keyboard when textview is pressed

extension UIView { 
    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(UIView.keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc func keyboardWillChange(_ notification: NSNotification) {
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY

        },completion: {(true) in
            self.layoutIfNeeded()
        })
    }
}

But when I press search bar then the screen moves up and search bar disappears. If I do view.bindToKeyboard() then the edittext is proper after displaying the keyboard.

One solution which I tried was binding the outlet of textview to keyboard but the textview disappears as soon as I start typing.

halfer
  • 19,824
  • 17
  • 99
  • 186
BraveEvidence
  • 53
  • 11
  • 45
  • 119

2 Answers2

2

I think the problem is that you are trying to know when the keyboard is going to appear. Searchbar has a textfield. So when it's tapped it opens the keyboard like your textview and the keyboardWillChange is called.

   keyboardWillChange(_ notification: NSNotification)

So the keyboard appears and hides your searchbar. You can detect searchbar tap and cancel the notification there.

    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool
    {
       //Dismiss your keyboard notification here

       return true
    }

You should use a library to handle this situation. I'm suggesting IQKeyboardManager. IQKeyBoardManager Github.

Somoy Das Gupta
  • 1,874
  • 1
  • 16
  • 19
0

I edit my earlier respond... have you try to put your searchBar into navigationBar?

something like this (just put on viewDidLoad):

navigationItem.titleView = searchBar
Hendra Kusumah
  • 186
  • 3
  • 6