How to enable cancel button with UISearchBar?

IphoneUisearchbarCancel Button

Iphone Problem Overview


In the contacts app on the iPhone if you enter a search term, then tap the "Search" button, the keyboard is hidden, BUT the cancel button is still enabled. In my app the cancel button gets disabled when I call resignFirstResponder.

Anyone know how to hide the keyboard while maintaining the cancel button in an enabled state?

I use the following code:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

The keyboard slides out of view, but the "Cancel" button to the right of the search text field is disabled, so that I cannot cancel the search. The contacts app maintains the cancel button in an enabled state.

I think maybe one solution is to dive into the searchBar object and call resignFirstResponder on the actual text field, rather than the search bar itself.

Any input appreciated.

Iphone Solutions


Solution 1 - Iphone

This method worked in iOS7.

- (void)enableCancelButton:(UISearchBar *)searchBar
{
    for (UIView *view in searchBar.subviews)
    {
        for (id subview in view.subviews)
        {
            if ( [subview isKindOfClass:[UIButton class]] )
            {
                [subview setEnabled:YES];
                NSLog(@"enableCancelButton");
                return;
            }
        }
    }
}

(Also be sure to call it anywhere after [_searchBar resignFirstResponder] is used.)

Solution 2 - Iphone

try this

for(id subview in [yourSearchBar subviews])
{
	if ([subview isKindOfClass:[UIButton class]]) {
		[subview setEnabled:YES];
	}
}

Solution 3 - Iphone

The accepted solution will not work when you start scrolling the table instead of tapping the "Search" button. In that case the "Cancel" button will be disabled.

This is my solution that re-enables the "Cancel" button every time it is disabled by using KVO.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // Search for Cancel button in searchbar, enable it and add key-value observer.
    for (id subview in [self.searchBar subviews]) {
        if ([subview isKindOfClass:[UIButton class]]) {
            [subview setEnabled:YES];
            [subview addObserver:self forKeyPath:@"enabled" options:NSKeyValueObservingOptionNew context:nil];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    // Remove observer for the Cancel button in searchBar.
    for (id subview in [self.searchBar subviews]) {
        if ([subview isKindOfClass:[UIButton class]])
            [subview removeObserver:self forKeyPath:@"enabled"];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    // Re-enable the Cancel button in searchBar.
    if ([object isKindOfClass:[UIButton class]] && [keyPath isEqualToString:@"enabled"]) {
        UIButton *button = object;
        if (!button.enabled)
            button.enabled = YES;
    }
}

Solution 4 - Iphone

As of iOS 6, the button appears to be a UINavigationButton (private class) instead of a UIButton.

I have tweaked the above example to look like this.

for (UIView *v in searchBar.subviews) {
    if ([v isKindOfClass:[UIControl class]]) {
        ((UIControl *)v).enabled = YES;
    }
}

However, this is obviously brittle, since we're mucking around with the internals. It also can enable more than the button, but it works for me until a better solution is found.

We should ask Apple to expose this.

Solution 5 - Iphone

This seemed to work for me (in viewDidLoad):

__unused UISearchDisplayController* searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];

I realize I should probably be using the UISearchDisplayController properly, but this was an easy fix for my current implementation.

Solution 6 - Iphone

You can use the runtime API to access the cancel button.

UIButton *btnCancel = [self.searchBar valueForKey:@"_cancelButton"];
[btnCancel setEnabled:YES];

Solution 7 - Iphone

I expanded on what others here already posted by implementing this as a simple category on UISearchBar.

UISearchBar+alwaysEnableCancelButton.h

#import <UIKit/UIKit.h>

@interface UISearchBar (alwaysEnableCancelButton)

@end

UISearchBar+alwaysEnableCancelButton.m

#import "UISearchBar+alwaysEnableCancelButton.h"

@implementation UISearchBar (alwaysEnableCancelButton)

- (BOOL)resignFirstResponder
{
    for (UIView *v in self.subviews) {
        // Force the cancel button to stay enabled
        if ([v isKindOfClass:[UIControl class]]) {
            ((UIControl *)v).enabled = YES;
        }

        // Dismiss the keyboard
        if ([v isKindOfClass:[UITextField class]]) {
            [(UITextField *)v resignFirstResponder];
        }
    }
    
    return YES;
}
@end

Solution 8 - Iphone

Here's a slightly more robust solution that works on iOS 7. It will recursively traverse all subviews of the search bar to make sure it enables all UIControls (which includes the Cancel button).

- (void)enableControlsInView:(UIView *)view
{
    for (id subview in view.subviews) {
        if ([subview isKindOfClass:[UIControl class]]) {
            [subview setEnabled:YES];
        }
        [self enableControlsInView:subview];
    }
}

Just call this method immediately after you call [self.searchBar resignFirstResponder] like this:

[self enableControlsInView:self.searchBar];

Voila! Cancel button remains enabled.

Solution 9 - Iphone

Till iOS 12, you can use like this:-

if let cancelButton : UIButton = self.menuSearchBar.value(forKey: "_cancelButton") as? UIButton{
    cancelButton.isEnabled = true
}

> > As of iOS 13, if you use like (forKey: "_cancelButton"), so this use of private API is caught and leads to a crash, > unfortunately.

For iOS 13+ & swift 5+

if let cancelButton : UIButton = self.menuSearchBar.value(forKey: "cancelButton") as? UIButton {
    cancelButton.isEnabled = true
}

Solution 10 - Iphone

I found a different approach for making it work in iOS 7.

What I'm trying is something like the Twitter iOS app. If you click on the magnifying glass in the Timelines tab, the UISearchBar appears with the Cancel button activated, the keyboard showing, and the recent searches screen. Scroll the recent searches screen and it hides the keyboard but it keeps the Cancel button activated.

This is my working code:

UIView *searchBarSubview = self.searchBar.subviews[0];
NSArray *subviewCache = [searchBarSubview valueForKeyPath:@"subviewCache"];
if ([subviewCache[2] respondsToSelector:@selector(setEnabled:)]) {
    [subviewCache[2] setValue:@YES forKeyPath:@"enabled"];
}

I arrived at this solution by setting a breakpoint at my table view's scrollViewWillBeginDragging:. I looked into my UISearchBar and bared its subviews. It always has just one, which is of type UIView (my variable searchBarSubview).

enter image description here

Then, that UIView holds an NSArray called subviewCache and I noticed that the last element, which is the third, is of type UINavigationButton, not in the public API. So I set out to use key-value coding instead. I checked if the UINavigationButton responds to setEnabled:, and luckily, it does. So I set the property to @YES. Turns out that that UINavigationButton is the Cancel button.

This is bound to break if Apple decides to change the implementation of a UISearchBar's innards, but what the hell. It works for now.

Solution 11 - Iphone

SWIFT version for David Douglas answer (tested on iOS9)

func enableSearchCancelButton(searchBar: UISearchBar){
    for view in searchBar.subviews {
        for subview in view.subviews {
            if let button = subview as? UIButton {
                button.enabled = true
            }
        }
    }
}

Solution 12 - Iphone

Most of the posted solutions are not robust, and will let the Cancel button get disabled under various circumstances.

I have attempted to implement a solution that always keeps the Cancel button enabled, even when doing more complicated things with the search bar. This is implemented as a custom UISearchView subclass in Swift 4. It uses the value(forKey:) trick to find both the cancel button and the search text field, and listens for when the search field ends editing and re-enables the cancel button. It also enables the cancel button when switching the showsCancelButton flag.

It contains a couple of assertions to warn you if the internal details of UISearchBar ever change and prevent it from working.

import UIKit

final class CancelSearchBar: UISearchBar {
	override init(frame: CGRect) {
		super.init(frame: frame)
		setup()
	}

	required init?(coder: NSCoder) {
		super.init(coder: coder)
		setup()
	}

	private func setup() {
		guard let searchField = value(forKey: "_searchField") as? UIControl else {
			assertionFailure("UISearchBar internal implementation has changed, this code needs updating")
			return
		}

		searchField.addTarget(self, action: #selector(enableSearchButton), for: .editingDidEnd)
	}

	override var showsCancelButton: Bool {
		didSet { enableSearchButton() }
	}

	@objc private func enableSearchButton() {
		guard showsCancelButton else { return }
		guard let cancelButton = value(forKey: "_cancelButton") as? UIControl else {
			assertionFailure("UISearchBar internal implementation has changed, this code needs updating")
			return
		}

		cancelButton.isEnabled = true
	}
}

Solution 13 - Iphone

Building on smileyborg's answer, just place this in your searchBar delegate:

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{	
    dispatch_async(dispatch_get_main_queue(), ^{
	    __block __weak void (^weakEnsureCancelButtonRemainsEnabled)(UIView *);
	    void (^ensureCancelButtonRemainsEnabled)(UIView *);
	    weakEnsureCancelButtonRemainsEnabled = ensureCancelButtonRemainsEnabled = ^(UIView *view) {
		    for (UIView *subview in view.subviews) {
			    if ([subview isKindOfClass:[UIControl class]]) {
				[(UIControl *)subview setEnabled:YES];
			    }
			    weakEnsureCancelButtonRemainsEnabled(subview);
		    }
	    };
	
	    ensureCancelButtonRemainsEnabled(searchBar);
    });
 }

This solution works well on iOS 7 and above.

Solution 14 - Iphone

For iOS 10, Swift 3:

for subView in self.movieSearchBar.subviews {
    for view in subView.subviews {
        if view.isKind(of:NSClassFromString("UIButton")!) {
            let cancelButton = view as! UIButton
            cancelButton.isEnabled = true
        }
    }
}

Solution 15 - Iphone

For iOS 9/10 (tested), Swift 3 (shorter):

searchBar.subviews.flatMap({$0.subviews}).forEach({ ($0 as? UIButton)?.isEnabled = true })

Solution 16 - Iphone

For iOS 11 and above, Swift 4-5:

extension UISearchBar {
  func alwaysShowCancelButton() {
    for subview in self.subviews {
      for ss in subview.subviews {
        if #available(iOS 13.0, *) {
          for s in ss.subviews {
            self.enableCancel(with: s)
          }
        }else {
          self.enableCancel(with: ss)
        }
      }
    }
  }
  private func enableCancel(with view:UIView) {
   if NSStringFromClass(type(of: view)).contains("UINavigationButton") {
      (view as! UIButton).isEnabled = true
    }
  }
}

UISearchBarDelegate

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    self.searchBar.resignFirstResponder()
    self.searchBar.alwaysShowCancelButton()
  }

Solution 17 - Iphone

for (UIView *firstView in searchBar.subviews) {
    for(UIView* view in firstView.subviews) {
        if([view isKindOfClass:[UIButton class]]) {
             UIButton* button = (UIButton*) view;
             [button setEnabled:YES];
        }
    }
}

Solution 18 - Iphone

You can create your CustomSearchBar inheriting from UISearchBar and implement this method:

- (void)layoutSubviews {
	
	[super layoutSubviews];
	
	@try {
		UIView *baseView = self.subviews[0];
		
		for (UIView *possibleButton in baseView.subviews)
		{
			if ([possibleButton respondsToSelector:@selector(setEnabled:)]) {
				[(UIControl *)possibleButton setEnabled:YES];
			}
		}
	}
	@catch (NSException *exception) {
		NSLog(@"ERROR%@",exception);
	}
}

Solution 19 - Iphone

A better solution is

[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil].enabled = YES;

Solution 20 - Iphone

Better & Easy method:

[(UIButton *)[self.searchBar valueForKey:@"_cancelButton"] setEnabled:YES];

Solution 21 - Iphone

Swift 5 & iOS 14

if let cancelButton : UIButton = self.menuSearchBar.value(forKey: "cancelButton") as? UIButton {
    cancelButton.isEnabled = true
}

Solution 22 - Iphone

One alternative that should be slightly more robust against UIKit changes, and doesn't reference anything private by name is to use the appearance proxy to set the tag of the cancel button. i.e., somewhere in setup:

let cancelButtonAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
cancelButtonAppearance.isEnabled = true
cancelButtonAppearance.tag = -4321

Then we can use the tag, here the magic number -4321 to find the tag:

extension UISearchBar {
    var cancelButton: UIControl? {
         func recursivelyFindButton(in subviews: [UIView]) -> UIControl? {
             for subview in subviews.reversed() {
                 if let control = subview as? UIControl, control.tag == -4321 {
                     return control
                 }
                 if let button = recursivelyFindButton(in: subview.subviews) {
                     return button
                 }
             }
             return nil
         }
         return recursivelyFindButton(in: subviews)
     }
}

And finally use searchBar.cancelButton?.isEnabled = true whenever the search bar loses focus, such as in the delegate. (Or if you use the custom subclass and call setShowsCancelButton from the delegate, you can override that function to also enable the button whenever it is shown.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristopherView Question on Stackoverflow
Solution 1 - IphoneDavid DouglasView Answer on Stackoverflow
Solution 2 - IphoneMalek_JundiView Answer on Stackoverflow
Solution 3 - IphoneMarián ČernýView Answer on Stackoverflow
Solution 4 - IphoneBen L.View Answer on Stackoverflow
Solution 5 - Iphonen8churView Answer on Stackoverflow
Solution 6 - IphoneBurhanuddin SunelwalaView Answer on Stackoverflow
Solution 7 - IphoneBrainsView Answer on Stackoverflow
Solution 8 - IphonesmileyborgView Answer on Stackoverflow
Solution 9 - IphoneVipul KumarView Answer on Stackoverflow
Solution 10 - IphoneMLQView Answer on Stackoverflow
Solution 11 - IphoneTal HahamView Answer on Stackoverflow
Solution 12 - IphoneDag ÅgrenView Answer on Stackoverflow
Solution 13 - IphonefollowbenView Answer on Stackoverflow
Solution 14 - IphoneSaoud RizwanView Answer on Stackoverflow
Solution 15 - IphoneneegraView Answer on Stackoverflow
Solution 16 - IphoneGiangView Answer on Stackoverflow
Solution 17 - IphoneAbdul RehmanView Answer on Stackoverflow
Solution 18 - IphoneDiego LimaView Answer on Stackoverflow
Solution 19 - IphonemigrantView Answer on Stackoverflow
Solution 20 - IphoneLal KrishnaView Answer on Stackoverflow
Solution 21 - IphoneoskarkoView Answer on Stackoverflow
Solution 22 - IphoneArkkuView Answer on Stackoverflow