Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 274
Ryan Avatar asked Jul 17 '15 04:07

Ryan


1 Answers

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.

like image 142
Boopathy Avatar answered Nov 15 '22 19:11

Boopathy