Search code examples
iosswiftswift3nsnotificationcenter

Get sender on NotificationCenter keyboard will show


I am currently working on an app with multiple text fields and 2 text views in one scroll view. On appearance of keyboard, I have been able to change the content inset of the scroll view in order to allow the fields to not be hidden. The problem I am having is I can only get this to work on one hardcoded field. I have to choose one and animate to it. Is there anyway to get the sender field or text view on keyboardWillShow? Currently, I am using this and everything works except as mentioned I had to choose one field detailsTxtView and animate to it. Any help?

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)),name: NSNotification.Name.UIKeyboardWillShow, object: nil)

func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        let contentInsets: UIEdgeInsets? = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
        scrollView.contentInset = contentInsets!
        scrollView.scrollIndicatorInsets = contentInsets!
        let goto = CGPoint(x: CGFloat(0.0), y: CGFloat(detailsTxtView.frame.origin.y + (keyboardSize.height + 40)))
        scrollView.setContentOffset(goto, animated: true)
    }

}

Solution

  • In iOS you can figure out who has the keyboard focus with UIResponder.isFirstResponder (note all UIViews inherit from UIResponder, so its a property on every view). Just check which field has isFirstResponder = true and scroll to that one. Its useful to put all of your fields into an outlet collection if you have a lot of them so you can just iterate through them and figure out which one isFirstResponder.