Monday, March 6, 2017

iOS: Keyboard hides TextField Solution in Swift 3.0



In iOS, it is a headache that you need to adjust each and every component  manually as per visibility. Most of the cases developer confused when he designed form and textfield is added at the bottom of the screen. In this case, System keyboard hides the textfield and user cannot see what he is entering.

To overcome this issue developer has to move up textfield while editing and also set it its default place when editing is done. If more textfield is added in single screen then this work gonna headache for every developer. 

Here, is the simple code to overcome this issue. You just need to add code for below steps:

1. IBOutlet textfield into the swift file (reference textfield in swift file)
2. add UITextFieldDelegate methods
3. add code for View move up and move down code

I have added complete code to over come the issue and will give you a exact solution as shown above.


class ViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var nameField: UITextField!
    override func viewDidLoad() {
        nameField.delegate = self

    override func didReceiveMemoryWarning() {

    func textFieldDidBeginEditing(_ textField: UITextField) {
            animateViewMoving(up: true, moveValue: 250)
    func textFieldDidEndEditing(_ textField: UITextField) {
            animateViewMoving(up: false, moveValue: 250)
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return true
    func animateViewMoving (up:Bool, moveValue :CGFloat){
        let movementDuration: TimeInterval = 0.3
        let movement:CGFloat = ( up ? -moveValue : moveValue)
        UIView.beginAnimations( "animateView", context: nil)
        UIView.setAnimationDuration(movementDuration )
        self.view.frame = self.view.frame.offsetBy(dx: 0,  dy: movement)

When user click "return" button from keyboard, textFieldShouldReturn method is called. So, it is recommended to resign keyboard thats why we have added this method.

Download Full Source Code

No comments:

Post a Comment