Hide UISearchBar Cancel Button
Solution 1
I managed to hide the "Cancel" button by subclassing UISearchBar
and override this method:
-(void)layoutSubviews{
[super layoutSubviews];
[self setShowsCancelButton:NO animated:NO];
}
Solution 2
I had the same issue, but fixed it a different way.
For those who can't or don't want to subclass UISearchDisplayController
, I fixed the issue by adding a listener on UIKeyboardWillShowNotification
, and setting [self setShowsCancelButton:NO animated:NO]
there.
In viewWillAppear:
:
// Add keyboard observer:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillAppear:)
name:UIKeyboardWillShowNotification
object:nil];
Then you create:
- (void)keyboardWillAppear:(NSNotification *)notification
{
[YOUR-SEARCHBAR-HERE setShowsCancelButton:NO animated:NO];
}
Don't forget to add,
[[NSNotificationCenter defaultCenter] removeObserver:self];
in viewWillDisappear:
!
Hope this helps!
Solution 3
Similar to Nimrod's answer, you can also subclass UISearchDisplayController
and implement the setActive:animated:
method:
- (void)setActive:(BOOL)visible animated:(BOOL)animated {
[super setActive:visible animated:animated];
self.searchBar.showsCancelButton = NO;
}
Solution 4
This seems to be a bug within Xcode. I submitted this error to Apple's bug reporting site, and they've followed up asking for more sample code and use-cases.
Thanks everyone for your attempt at solving this problem.
Solution 5
class CustomSearchBar: UISearchBar {
override func setShowsCancelButton(showsCancelButton: Bool, animated: Bool) {
super.setShowsCancelButton(false, animated: false)
}
}
class CustomSearchController: UISearchController, UISearchBarDelegate {
lazy var _searchBar: CustomSearchBar = {
[unowned self] in
let customSearchBar = CustomSearchBar(frame: CGRectZero)
customSearchBar.delegate = self
return customSearchBar
}()
override var searchBar: UISearchBar {
get {
return _searchBar
}
}
}
![ArtSabintsev](https://i.stack.imgur.com/YDsQN.jpg?s=256&g=1)
Comments
-
ArtSabintsev over 3 years
I have a UISearchDisplayController and UISearchBar hooked up to my ViewController via Outlets from my nib.
I'd like to hide the cancel button so that the user never sees it. The problem is that the following code hides the button, but only after displaying it to the user for a millisecond (e.g., it flashes on the simulator and device and then disappears out of view).
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller { controller.searchBar.showsCancelButton = NO; }
Is there a better way to hide it?