Mohammed
Mohammed

Reputation: 1504

Cancel button disappears after dismissing UISearchBar keyboard

I have the following lines in my code:

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchBar.showsCancelButton = true
}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
}

When I tap the searchButton, the keyboard is dismissed and the cancel button disappears.

What is the solution ?

Upvotes: 3

Views: 865

Answers (1)

Mohammed
Mohammed

Reputation: 1504

SOLVED !

I have solved the problem by adding UIButton [cancelButton] beside the UISearchBar, and adds the width constraint as @IBOutlet. Now, instead of showing the cancelButton of the searchBar, I'm changing the width of the cancelButton to show or hide as follow:

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    UIView.animateWithDuration(0.25) {
        self.widthConstraint.constant = 44.0
        self.cancelButton.layoutIfNeeded()
    }
}

@IBAction func cancelButtonTapped(sender: UIButton) {
    UIView.animateWithDuration(0.25) {
        self.widthConstraint.constant = 0.0
        self.cancelButton.layoutIfNeeded()
    }
}

Upvotes: 1

Related Questions