Material: TextField in SearchBar cannot become the first responder

Created on 27 Aug 2017  路  6Comments  路  Source: CosmicMind/Material

I was trying to make the textField in searchBar the first responder, but it always failed.

What I have done:

  • searchBar.textField.canBecomeFirstResponder returns true
  • searchBar.textField.becomeFirstResponder() returns false
  • look for the current first responder but returns nil
func findFirstResponder() -> Any?
    {
        if (self.isFirstResponder) {
            return self
        }
        for subView in self.view.subviews {
            if subView.isFirstResponder {
                return subView
            }
        }
        return nil
    }

I don't know whether I was missing something or It seems to be a bug.
Any help would be appreciated.

  • Xcode 9 beta 5
  • iOS 10.3
help wanted investigate

Most helpful comment

Hey, so you need to call becomeFirstResponder() when the view controller has appeared, like so:

open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        searchBar.textField.becomeFirstResponder()
    }

:) All the best!

All 6 comments

When are you calling this function? Can you send me a sample with this and I will take a look?

@danieldahan
I use the Search Sample from https://github.com/CosmicMind/Samples
I try to add searchBar.textField.becomeFirstResponder() in two places.

  • prepareSearchBar() in AppSearchBarController.swift
  • prepareSearchBar() in RootViewController.swift

Thanks for you time ;)

Yeah, I can see it is not working. Weird, well I shall take a look :)

Hey, so you need to call becomeFirstResponder() when the view controller has appeared, like so:

open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        searchBar.textField.becomeFirstResponder()
    }

:) All the best!

That works! Thank you! ;)
I should have investigated the view life cycles better.

No worries :) I am happy to help.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sovata8 picture sovata8  路  15Comments

mohpor picture mohpor  路  43Comments

timoschwarzer picture timoschwarzer  路  16Comments

ijameelkhan picture ijameelkhan  路  23Comments

ayham-achami picture ayham-achami  路  26Comments