3

I have a subclass of UITableViewController that displays several rows (8 to be exact), where the top row is a custom cell that contains a UITextField. When the view is loaded, I have the keyboard popup immediately by calling becomeFirstResponder on that textfield. This all worked fine until I upgraded from iOS 9 to iOS 10. Now the view jumps to the bottom of the view, with the keyboard covering my last two rows and my TextField is off the visible area. When I comment out the becomeFirstResponder call, the jumping goes away, but I lose my keyboard popup of course. This is what my code looks like...

class UserProfileTableViewController: UITableViewController {

  private var userInfoCell: UserInfoTableViewCell?
  ...

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

  if indexPath.section == 0 {
    userInfoCell = tableView.dequeueReusableCellWithIdentifier("userInfoCell", forIndexPath: indexPath) as? UserInfoTableViewCell

    if !editMode {
      userInfoCell?.nameField.becomeFirstResponder()
    }

    return userInfoCell!
  }
  else if indexPath.section == 1 {
   ....

Then my custom table view cell looks like this...

class UserInfoTableViewCell: UITableViewCell, UITextFieldDelegate,, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
...

override func awakeFromNib() {
  super.awakeFromNib()
  // listen for when user touches a textfield
  nameField.delegate = self
  ...
}

override func setSelected(selected: Bool, animated: Bool) {
  super.setSelected(selected, animated: animated)
}

...

Things I have tried:

  1. Calling userInfoCell?.nameField.becomeFirstResponder() in viewWillAppear()
  2. Calling userInfoCell?.nameField.becomeFirstResponder() in viewDidAppear()
  3. Calling nameField.becomeFirstResponder() in UserInfoTableViewCell.awakeFromNib().
  4. Calling tableView.scrollToRowAtIndexPath() after the call to userInfoCell?.nameField.becomeFirstResponder().
  5. removing super.viewWillAppear() in my viewWillAppear()

None of these have worked for me.

Bista
  • 7,869
  • 3
  • 27
  • 55
Coder1224
  • 1,785
  • 2
  • 17
  • 21

1 Answers1

0

deferring becomeFirstResponder() solved the issue for me

dispatch_async(dispatch_get_main_queue(), {
    userInfoCell?.nameField.becomeFirstResponder()
})
Maciek
  • 21
  • 1
  • That made it where the screen stays at the top for me as well! However, now when the screen segues to the table there is a strange flicker of a keyboard, then that goes away then another keyboard comes up. Maybe because its called in a tableview delegate so is called multiple times??? I've seen this `dispatch_async()` as a solution on many SO posts, but I hesitate to create threads as a general rule. Is that all that method does - create a thread to wait until the main thread is ready for it? – Coder1224 Oct 08 '16 at 00:00