How to make UITextField keep track of keyboard level when typing

2

I have a problem, I created an app that has a form where it has 6 UITextField , but I have a problem when running the app on an iphone4 the keyboard overlays some UITextField and I can not see the text I'm typing in, I've placed a UIScrollView so that the user can scroll the page but I'd like it when the user focuses on the field it's raised to the keyboard level as well type in WhatsApp, and when finishing the typing the same return the current position, could someone help me?

    
asked by anonymous 27.08.2015 / 15:29

2 answers

2

This is very simple to do and very common as well.

The idea of this example I'm going to pass is as follows, get the time the keyboard takes to go up or down and get the height it will occupy on the screen.

The first thing you need to do is to add a handler to the UIKeyboardWillChangeFrameNotification event, which will notify you when the keyboard is rising or falling (you will notice that whether it goes up or down does not really matter) / p>

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(onKeyboardChange(_:)), name:UIKeyboardWillChangeFrameNotification, object: nil);

And the onKeyboardChange handler, which should be available in the self scope, looks like this:

func onKeyboardChange (notification: NSNotification )
{
    let screenBounds = UIScreen.mainScreen().bounds
    let info = notification.userInfo!
    let keyboardFrame = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

    duration = info[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
    let height = screenBounds.height - keyboardFrame.origin.y

    // Daqui em diante, você pode animar suas views usando a duração
    // e o height obtidos acima
}

Notice that when you apply height it will already vary the vertical position of the elements that you want to raise or lower in the UI, ie it does not matter if the keyboard is going up or down :)

And do not forget to remove the observer from the UIKeyboardWillChangeFrameNotification event when you are no longer using it

NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)

That's it.

    
17.07.2016 / 20:42
4

The TPKeyboardAvoiding library does this work.

After adding the library to the project, modify the class of the UIScrollView object that you had previously added to TPKeyboardAvoidingScrollView.

    
27.08.2015 / 16:21