Search code examples
iosswiftbuttonsearchbar

Search Bar - Cancel Button in Navigation Bar


I'm doing Search Bar in Navigation Bar. When I'm editing I don't have Cancel Button on right side of navigation Bar.

Tried:

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {

    var barButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Done, target: self, action: "")
    self.navigationItem.rightBarButtonItem = barButton
}

enter image description here

enter image description here

EDIT:

I added search bar to nav bar like this:

lazy var searchBar:UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 300, 20))

        searchBar.placeholder = "Hľadať"
        searchBar.barStyle = UIBarStyle.BlackTranslucent
        var leftNavBarButton = UIBarButtonItem(customView:searchBar)
        self.navigationItem.leftBarButtonItem = leftNavBarButton

Solution

  • Do it in this way:

    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        var cancelSearchBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBarButtonItemClicked")
        self.navigationItem.setRightBarButtonItem(cancelSearchBarButtonItem, animated: true)
        return true
    }
    

    And in the "Cancel" handler:

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        // closes the keyboard
        searchBar.resignFirstResponder()
    
        // If you are using a search controller
        // self.searchDisplayControllerCustom.setActive(false, animated: true)
    
        // remove the cancel button
        self.navigationItem.setRightBarButtonItem(nil, animated: true)
    }
    
    func cancelBarButtonItemClicked() {
        self.searchBarCancelButtonClicked(self.searchBar)
    }
    

    And set the correct color for the navigation bar title text:

    // This sets the textcolor for all navigation bars in the app
    // Do this in the app delegate on startup
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
    

    And add the delegate:

    searchBar.delegate = self