Hiding Cancel Button on Search Bar in Uisearchcontroller

Hiding Cancel button on search bar in UISearchController

I ended up subclassing both UISearchBar and UISearchController as suggested:

CustomSearchBar.swift

import UIKit

class CustomSearchBar: UISearchBar {

override func layoutSubviews() {
super.layoutSubviews()
setShowsCancelButton(false, animated: false)
}
}

CustomSearchController.swift

import UIKit

class CustomSearchController: UISearchController, UISearchBarDelegate {

lazy var _searchBar: CustomSearchBar = {
[unowned self] in
let result = CustomSearchBar(frame: CGRectZero)
result.delegate = self

return result
}()

override var searchBar: UISearchBar {
get {
return _searchBar
}
}
}

iOS8 Cannot hide cancel button on search bar in UISearchController

I think there are three ways of achieving that:

  1. Override searchDisplayControllerDidBeginSearch and use the following code:

searchController.searchBar.showsCancelButton = false


  1. Subclass UISearchBar and override the layoutSubviews to change that var when the system attempts to draw it.

  2. Register for keyboard notification UIKeyboardWillShowNotification and apply the code in point 1.

Of course can always implement your search bar.

Is there a way to only activate the cancel button on a search bar while editing?

If you don't want the search bar to appear until the user actually taps on the search bar of the search controller, don't add any code for the cancel button. The default behavior is to not show the cancel button until the user activates search.

Simply remove any code you have to setup or change the cancel button.

As of iOS 13 you can use the automaticallyShowsCancelButton property of UISearchController but in iOS it defaults to true. It seems to default to false under Mac Catalyst.

How to disable cancel button of UISearchController.seachBar when i tap at searchBar?

You can create a custom class and subclass UISearchBar and UISearchViewController.
For example:-

class CustomizedSearchBar: UISearchBar {
override func layoutSubviews() {
super.layoutSubviews()
setShowsCancelButton(false, animated: false)
}
}

Now Create Object of the CustomizedSearchBar and use it within other viewController.

Or you can create a customized searchViewController as follows:

class CustomizedSearchController: UISearchController, UISearchBarDelegate {

lazy var _searchBar: CustomSearchBar = {
[unowned self] in
let result = CustomSearchBar(frame: CGRectZero)
result.delegate = self

return result
}()

override var searchBar: UISearchBar {
get {
return _searchBar
}
}
}

Please follow this link for more detail information.



Related Topics



Leave a reply



Submit