ben fo
ben fo

Reputation: 21

Add full searchBar to navigation

I am adding a search bar to my navigation bar like this

    searchBar.showsCancelButton = false
    searchBar.placeholder = "Search"
    searchBar.delegate = self
    searchBar.enablesReturnKeyAutomatically = true
    self.navigationItem.titleView = searchBar

but i have bar button items is there a way to hide this and make the searchBar full length

Upvotes: 1

Views: 499

Answers (1)

Joe
Joe

Reputation: 8986

Try this Code:

Note: Code Updated with barButton hide function when searchBar is active and back in when cancel button pressed.

class ViewController: UIViewController,UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate {

var resultSearchController : UISearchController!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.resultSearchController = UISearchController(searchResultsController:  nil)

    self.resultSearchController.searchResultsUpdater = self
    self.resultSearchController.delegate = self
    self.resultSearchController.searchBar.delegate = self
    self.resultSearchController.hidesNavigationBarDuringPresentation = false
    self.resultSearchController.dimsBackgroundDuringPresentation = true
    self.definesPresentationContext = true 

    self.navigationItem.titleView = resultSearchController.searchBar

    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Your Button", style: .plain, target: self, action: #selector(addTapped))

}

func updateSearchResults(for searchController: UISearchController) {

    // You have to implement search delegate method here to make it work.

    if resultSearchController.isActive == true {

        self.navigationItem.rightBarButtonItem = nil
    }  else {       

    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Your Button", style: .plain, target: self, action: #selector(addTapped))
    }
   }


func addTapped() {
    // You can do your stuff here. when your button pressed...
    print("Button Pressed")

   } 
}

Output:

enter image description here

Upvotes: 1

Related Questions