Ryan
Ryan

Reputation: 22247

How to add another textfield to UISearchController when focus is on Search Bar?

I'm trying to add another textfield for a 'Location' input to a UISearchController when the user focuses on the Search Bar, just below the Search Bar on the navigation bar.

Example of what I have and where I'd like it to go:

enter image description here

I've tried something like this, which doesn't work:

var searchController: UISearchController!

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    var myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200.00, height: 40.00))
    myTextField.backgroundColor = UIColor.purpleColor()
    myTextField.text = "Location"
    myTextField.borderStyle = UITextBorderStyle.None
    searchController.view.addSubview(myTextField)
}

Any help would be great! Thanks.

Upvotes: 10

Views: 1900

Answers (2)

Boopathy
Boopathy

Reputation: 415

Don't know whether you found your answer or not. Let me suggest my solution.

Nothing wrong in your code. It works fine. But the reason why it doesn't show is , when you click in the search bar func searchBarTextDidBeginEditing(searchBar: UISearchBar) has no effect on it because you might forget to set the delegate for the search bar.

I tried your code and after setting the delegate it just works fine. Also it hides behind the navbar as the Y position is 0. The solution is,

  1. Add the UISearchBarDelegate to your class
  2. In viewDidLoad()

      override func viewDidLoad(){
        super.viewDidLoad()
        searchcontroller.searchbar.delegate = self
        }
    
  3. In searchBarTextDidBeginEditing

       func searchBarTextDidBeginEditing(searchBar: UISearchBar) {           
    
        var myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: searchController.searchBar.frame.height + 20, width: view.frame.size.width, height: 40.00))
        myTextField.backgroundColor = UIColor.purpleColor()
        myTextField.text = "Location"
        myTextField.borderStyle = UITextBorderStyle.None
        searchController.view.addSubview(myTextField)
    }
    

Hope it helps.

Upvotes: 4

Ramkumar chintala
Ramkumar chintala

Reputation: 958

Try like This:

you just create a custom NavigationBar add your text field to that and override the SearchController Delegate Methods

try it may works .

Upvotes: 1

Related Questions