Skip to content

Instantly share code, notes, and snippets.

@ilia3546
Created March 14, 2024 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilia3546/f27e016b60dfe3a9fe8b5caa2854198d to your computer and use it in GitHub Desktop.
Save ilia3546/f27e016b60dfe3a9fe8b5caa2854198d to your computer and use it in GitHub Desktop.
Add a custom button between UISearchBar and Cancel button while a search is enabled
private lazy var customSearchButton = UIButton(
type: .contactAdd,
primaryAction: UIAction(handler: { _ in })
)
private func configureSearchController() {
let searchController = UISearchController(searchResultsController: /*YOUR_SEARCH_CONTROLLER*/)
searchController.delegate = self
// Set custom leading padding to the cancel button (size of our button + some padding)
searchController.searchBar.perform(Selector(("_setAdditionalPaddingForCancelButtonAtLeadingEdge:")), with: Double(40))
// Add our custom button to the _UISearchBarSearchContainerView and attach to the searchTextField
let searchTextField = searchController.searchBar.searchTextField
if let searchTextFieldContainerView = searchTextField.superview {
searchTextFieldContainerView.addSubview(self.customSearchButton)
self.customSearchButton.alpha = 0
self.customSearchButton.snp.makeConstraints { make in
make.size.equalTo(36)
make.left.equalTo(searchTextField.snp.right).offset(8)
make.centerY.equalTo(searchTextField)
}
}
}
func willPresentSearchController(_ searchController: UISearchController) {
UIView.animate(withDuration: 0.25) { self.customSearchButton.alpha = 1 }
}
func willDismissSearchController(_ searchController: UISearchController) {
UIView.animate(withDuration: 0.25) { self.customSearchButton.alpha = 0 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment