How to make Uitextfield track keyboard level when typing

Asked

Viewed 194 times

2

I have a little problem, I created an app that has a form where has 6 Uitextfield, but I have a problem running the app on an Iphone4 keyboard overlaps some Uitextfield and I can’t see the text I’m typing, I put a Uiscrollview so that the user can scroll the page but I would like when the user focus on the field it is raised to the level of the keyboard as when typing in Whatsapp, and when finishing typing the same goes back to the current position, someone could help me?

2 answers

4

The library Tpkeyboardavoiding does that job.

After adding the library to the project, modify the class of the Uiscrollview object you had already added to Tpkeyboardavoidingscrollview.

  • Thank you very much, Rafael.

2


This is very simple to do and common good too.

The idea of this example that I will pass is the following, get the time that the keyboard takes to climb or descend and get the height that it will occupy on the screen.

The first thing you need to do is add an Handler to the event UIKeyboardWillChangeFrameNotification, that will notify you when the keyboard is going up or down (you will notice that knowing whether it goes up or down doesn’t matter much).

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

And the Handler onKeyboardChange, which must be available in scope self gets 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
}

Note that when you apply the height it will already vary the vertical position of the elements that you want to go up or down in the UI, that is, it doesn’t matter if the keyboard is going up or down :)

And don’t forget to remove Observer from the event UIKeyboardWillChangeFrameNotification when no longer using it

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

That’s it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.