简体   繁体   中英

Swift : scroll the view up when keyboard shows

I have a scrollView that i want to scroll up when the keyboard is shown.

I have a crash with this error when the keyboard show :

2014-09-29 14:48:50.738 swrd[1563:472888] -[swrd.EditPhotoViewController keyboardWasShown]: unrecognized selector sent to instance 0x14ed36640

Here is my code, what's wrong ?:

   func registerForKeyboardNotifications ()-> Void   {

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown", name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden", name: UIKeyboardWillHideNotification, object: nil)


}

func deregisterFromKeyboardNotifications () -> Void {
    let center:  NSNotificationCenter = NSNotificationCenter.defaultCenter()
    center.removeObserver(self, name: UIKeyboardDidHideNotification, object: nil)
    center.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)


}


 func keyboardWasShown (notification: NSNotification) {

    let info : NSDictionary = notification.userInfo!
    let keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.frame

    let insets: UIEdgeInsets = UIEdgeInsetsMake(self.scrollView.contentInset.top, 0, keyboardSize!.height, 0)

    self.scrollView.contentInset = insets
    self.scrollView.scrollIndicatorInsets = insets

    self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x, self.scrollView.contentOffset.y + keyboardSize!.height)

}

func keyboardWillBeHidden (notification: NSNotification) {

    let info : NSDictionary = notification.userInfo!
    let keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.frame

    let insets: UIEdgeInsets = UIEdgeInsetsMake(self.scrollView.contentInset.top, 0, keyboardSize!.height, 0)

    self.scrollView.contentInset = insets
    self.scrollView.scrollIndicatorInsets = insets



}


 override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)



   self.registerForKeyboardNotifications()

}

 override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(true)

    self.deregisterFromKeyboardNotifications()

}

In your code, keyboardWasShown and keyboardWasHidden each take an argument, the NSNotification . You need to terminate your selectors in addObserver with a colon so that it gets passed. Ie, keyboardWasShown and keyboardWasShown: are different selectors.

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)

See a self-contained solution below:

private func startObservingKeyboardEvents() {
  NSNotificationCenter.defaultCenter().addObserver(self,
    selector:Selector("keyboardWillShow:"),
    name:UIKeyboardWillShowNotification,
    object:nil)
  NSNotificationCenter.defaultCenter().addObserver(self,
    selector:Selector("keyboardWillHide:"),
    name:UIKeyboardWillHideNotification,
    object:nil)
}

private func stopObservingKeyboardEvents() {
  NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
  NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(notification: NSNotification) {
  if let userInfo = notification.userInfo {
    if let keyboardSize: CGSize = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size {
      let contentInset = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
    }
  }
}

func keyboardWillHide(notification: NSNotification) {
  let contentInset = UIEdgeInsetsZero;
}

Use the contentInset variable to adjust the content insets.

In my case, was need some changes in the codes above:

1 - First you need put a Scrollview in your view, and set constraints like this:

在此输入图像描述

It's important your scrollView be grater than view.

2 - Put your TextField's and other components you need.

3 - Link ScrollView to the ViewController with @IBOutlet

4 - Add the Delegate to ScrollView:

class ViewController: UIViewController, UITextFieldDelegate,     UIScrollViewDelegate {
...

5 - Add the Observer's:

override func viewWillAppear(animated: Bool) {
   self.startKeyboardObserver()
}

override func viewWillDisappear(animated: Bool) {
   self.stopKeyboardObserver()
}


private func startKeyboardObserver(){
  NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) //WillShow and not Did ;) The View will run animated and smooth
  NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

private func stopKeyboardObserver() {
  NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
  NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

6 - Add The code to scroll, calculating KeyboardSize.

func keyboardWillShow(notification: NSNotification) {
      if let userInfo = notification.userInfo {
         if let keyboardSize: CGSize =    userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size {
            let contentInset = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height,  0.0);

        self.scrollView.contentInset = contentInset
        self.scrollView.scrollIndicatorInsets = contentInset

        self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x, 0 + keyboardSize.height) //set zero instead self.scrollView.contentOffset.y

       }
    }
 }

func keyboardWillHide(notification: NSNotification) {
    if let userInfo = notification.userInfo {
       if let keyboardSize: CGSize =  userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size {
          let contentInset = UIEdgeInsetsZero;

        self.scrollView.contentInset = contentInset
        self.scrollView.scrollIndicatorInsets = contentInset
        self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x, self.scrollView.contentOffset.y)
       }
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM