Guodong Rong Guodong Rong - 1 year ago 120
Swift Question

IOS Swift beginner

In a screen, view-scrollview-contentview, there are a lot of textfields in the contentview so I use a scrollview to make them in one screen.Now the problem is I could not click or type in the textfield because I know the scrollview has covered the contentview. But I want to type in the textfield and be able to scroll the screen as well. I tried to see a lot of answers here but could not figure out the correct solution.
Both the scrollview and contentview are user interaction enabled, switch on/off the "delays content touches"/"Cancellable content touches" in scrollview but doesn't work.
Appreciate any help.

Answer Source

Just create two notifications (once when the keyboard appears and other when it dissapear) on the viewDidLoad :

  //Notifications for keyBoard when appears.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name:UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide), name:UIKeyboardWillHideNotification, object:  nil)

then call the function which calculates the padding and make an scroll.

func keyboardWillShow(notification:NSNotification){
        var userInfo = notification.userInfo!
        var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
        keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)

        var contentInset:UIEdgeInsets = self.scrollview.contentInset
        contentInset.bottom = keyboardFrame.size.height
        self.scrollview.contentInset = contentInset

func keyboardWillHide(notification:NSNotification){
        var contentInset:UIEdgeInsets = UIEdgeInsetsZero
        self.scrollview.contentInset = contentInset
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download