Content Locked Under Keyboard: Another Approach To Solve

If you are an iOS developer very likely you faced this problem: when a user clicks on some field to type, the keyboard pops up and covers the text field.

Recently I had this problem as well, looking for a solution I found this link from Apple's iOS Developer Library.

Despite the good source, I didn't like having to place my views (like UITextField) inside a UIScrollView to solve this matter.

Another Approach To Solve

I found a simpler way, did some changes and then wrapped it in a UIViewController:

import UIKit

class UncoveredContentViewController: UIViewController {
  var activeField: UIView?
  var changedY = false
  var keyboardHeight: CGFloat = 300

  override func viewDidLoad() {
    super.viewDidLoad()

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

  func keyboardWillShow(sender: NSNotification) {
    let kbSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size

    keyboardHeight = kbSize!.height
    var aRect = self.view.frame;
    aRect.size.height = aRect.size.height - kbSize!.height - CGFloat(20);

    if activeField != nil && !CGRectContainsPoint(aRect, activeField!.frame.origin) {
      if (!changedY) {
        self.view.frame.origin.y -= keyboardHeight
      }
      changedY = true
    }
  }

  func keyboardWillHide(sender: NSNotification) {
    if changedY {
      self.view.frame.origin.y += keyboardHeight
    }
    changedY = false
  }

  deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self);
  }

  @IBAction func textFieldEditingDidBegin(sender: UITextField){
    //println("did begin")
    activeField = sender
  }

  @IBAction func textFieldEditingDidEnd(sender: UITextField) {
    //println("did end")
    activeField = nil
  }
}

There is no secret here. We observe UIKeyboardWillShowNotification and UIKeyboardWillHideNotification calling its respective bound methods when the events are fired.

The handler methods then scroll up/down the parent view according to keyboard's height.

In the controllers you need this solution, just subclass UncoveredContentViewController:

import UIKit

class ViewController: UncoveredContentViewController {
}

At last, don't forget to bind Editing Did Begin and Editing Did End to textFieldEditingDidBegin and textFieldEditingDidEnd respectively for each UITextField you need to fix.

That's all. See you.

Written on September 26, 2015

Share: