Cancel button in searchBar ios 8 - search

tell me how to change the text on the Cancel button in searchBar?
Image: http://i.stack.imgur.com/8G1ZM.png

you can do that in this delegate method of UISearchBar
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
[theSearchBar setShowsCancelButton:YES animated:NO];
for (UIView *subView in theSearchBar.subviews){
if([subView isKindOfClass:[UIButton class]]){
[(UIButton*)subViewsetTitle:#"Button Title"forState:UIControlStateNormal];
}
}
}
UPDATE
after a long way searching the only way i got working in swift
is to set a custom UIBarButtonItem but you will need to show the search bar on the navigation
in ViewDidLoad()
self.searchDisplayController?.displaysSearchBarInNavigationBar = true
and in Delegate Method
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
var barButton = UIBarButtonItem(title: "Button Title", style: UIBarButtonItemStyle.Done, target: self, action: "here")
self.searchDisplayController?.navigationItem.rightBarButtonItem = barButton
}
i hope that works with you
«Another UPDATE
as you said in comments you will need to localize your application, in your case you will only need to localize the storyBoard
first navigate to your project settings then info, under localizations click the + button and add your own languages then check only StoryBoard
and now you have localized your app but you might don't see the changes until you remove the app and install it again or if the device language is set to english you will need to write 2 lines of code to change the language manually here is it
var str:NSString = "ar" // ar stands for arabic you put here you own language small character
var myArray:NSArray = [str]
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "AppleLanguages")
and your button will looks like this
if you want to know more about localization see this Internationalization Tutorial for iOS [2014 Edition]
if you still need help till me :)

There are 2 solutions.
set key/value
[self.searchController.searchBar setValue:#"취소" forKey:#"_cancelButtonText"];
This solution works well, but you have to know that _cancelButtonText property is not public property.(You can not find this property in the documentation page.)
And It's not sure that this solution can pass the apple review process. So, use solution 2 please.
use a delegate.
You can change cancel button title(iOS8) within willPresentSearchController method.
(Assume that the searchBar is in tableView headerView)
- (void)willPresentSearchController:(UISearchController *)searchController{
// You have to set YES showsCancelButton.
// If not, you can not change your button title when this method called
// first time.
self.searchController.searchBar.showsCancelButton = YES;
UIView* view=self.searchController.searchBar.subviews[0];
for (UIView *subView in view.subviews) {
if ([subView isKindOfClass:[UIButton class]]) {
// solution 1
UIButton *cancelButton = (UIButton*)subView;
[cancelButton setTitle:NSLocalizedString(#"취소", nil) forState:UIControlStateNormal];
}
}
}
Also, You can get infomation about the searchBar through a view debugging tools in Xcode. Set a breakPoint at the willPresentSearchController method.
Good luck.

Actually, the cancel button is not a top view in the Search bar. You should search for it recursively.
-(UIButton*)findButtonInView:(UIView*)v{
for (UIView *subView in v.subviews){
if([subView isKindOfClass:[UIButton class]]){
return (UIButton*)subView;
}else if([subView isKindOfClass:[UIView class]]){
UIButton* btn = [self findButtonInView:subView];
if(btn){
return btn;
}
}
}
return nil;
}
//...
UIButton* searchButton = [self findButtonInView:self.searchBar];

Related

WKWebView not rendering correctly in iOS 10

I have WKWebView inside the UITableViewCell. The web view load request and then after finished loading, I'll resize the web view height to be equal to its content height, then adjust table view cell height to fit accordingly.
What happened was the web view only displays the area that fit the screen size. When I scroll down, everything is white. But I see that the web view rendered with correct height, tap and hold on the white area on the web view still see selection. Zooming with pinch makes the web view area that displaying on the screen visible, but other areas sometimes become white.
It works fine on iOS 8 and 9. I have created a sample project to demonstrate this behaviour here:
https://github.com/pawin/strange-wkwebview
Open Radar:
https://openradar.appspot.com/radar?id=4944718286815232
Update: This issue is resolved in iOS11
You need to force the WKWebView to layout while your UITableView scrolls.
// in the UITableViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
if let tableView = scrollView as? UITableView {
for cell in tableView.visibleCells {
guard let cell = cell as? MyCustomCellClass else { continue }
cell.webView?.setNeedsLayout()
}
}
}
func reloadWKWebViewIfNeeded() {
for cell in self.tableView.visibleCells {
guard let webviewCell = cell as? WebviewCell else { continue }
// guard cell height > screen height
webviewCell.webview.reload()
}
}
override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard !decelerate else { return }
self.reloadWKWebViewIfNeeded()
}
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
self.reloadWKWebViewIfNeeded()
}
Not the best solution though, but at least user can see the rest of the content
I have the same problem - add a WKWebView to a UITableViewCell, and I solved this problem by these steps:
1.Create a UITextView instance and add it to UITableView's superview(UIViewControllew.view)
2.implement codes in scrollViewDidScroll like this:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self.xxtextView becomeFirstResponder];
[self.xxtextView resignFirstResponder];
}
These codes may cause increased cpu performance overhead, you can fix it by some way such us use a temp variable as threshold value.
I don't think this is a perfect solve method, but it works for me.
Eventually I realized that textview becomeFirstResponder just led the webview layout again, so you can just fix it like this:
CGFloat tempOffset = 0;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (!tempOffset || ABS(scrollView.contentOffset.y - tempOffset) > ScreenHeight/2)
{
[self.wkWebView setNeedsLayout];
tempOffset = scrollView.contentOffset.y;
}
}
In objective-C this is how I solve the problem.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
NSArray * visibleCell = [self.tableView visibleCells];
for (CustomUITableViewCell * cell in visibleCell) {
if ([cell isKindOfClass:[CustomUITableViewCell class]]) {
[cell.wkWebView setNeedsLayout];
}
}
}
That code will collect all visible cell and do the setNeedsLayout in fast enumeration during user scroll.
Im also have uitableview with cell with wkWebView. And i stack with same problem. But timely you can fix this with this code. By performance do not worry. I tested this solution on iphone 5s and it was taken 10-15% CPU only when you scrolling uitableView with visible web cell.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//TODO: Remove this fix when WKWebView will fixed
if let cell = tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as? WKWebViewCell {
// Here we take our cell
cell.wkWebView?.setNeedsLayout()
// here is "magic" (where wkWebView it is WKWebView, which was
// previously added on cell)
}
}

Show UIAlertController over keyboard

In iOS 8 and lower show a UIActionSheet when keyboard is presented will present the action sheet over the keyboard. With iOS 9 this is no longer the case.
In my app we have a chat functionality and want the show a action over the keyboard. We used to use UIActionSheet which worked fine until iOS 8. In iOS 9 the action sheet is present behind the keyboard. I've tried both UIActionSheet and UIAlertController.
What we want is a action sheet like in messages.app
I've tried placing the action sheet in it own window and overriding canBecomeFirstResponder which just made the keyboard disappear.
I have implemented exactly this in our app. The trick is to have the alert controller appear on a different window. This is how the UIActionSheet implementation does it, and works great on iOS 8, but on 9, Apple has moved the keyboard implementation to a window which has a very high window level (10000000). The fix is to give your alert window an even higher window level (as a custom double value, not using the provided constants).
When using a custom window which will have transparency, make sure to read my answer here, regarding background color, to prevent window becoming black during rotation transitions.
_alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
_alertWindow.rootViewController = [UIViewController new];
_alertWindow.windowLevel = 10000001;
_alertWindow.hidden = NO;
_alertWindow.tintColor = [[UIWindow valueForKey:#"keyWindow"] tintColor];
__weak __typeof(self) weakSelf = self;
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Test" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[alert addAction:[UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
weakSelf.alertWindow.hidden = YES;
weakSelf.alertWindow = nil;
}]];
[alert addAction:[UIAlertAction actionWithTitle:#"Test" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
weakSelf.alertWindow.hidden = YES;
weakSelf.alertWindow = nil;
}]];
[_alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];
The answer supplied by Leo is broken as of iOS 11, because Apple now prevents you from setting a windowLevel above 10000000. A fix is to implement a custom UIWindow and override the windowLevel receiver:
#interface TopWindow : UIWindow #end
#implementation TopWindow
- (UIWindowLevel) windowLevel {
return 20000000.000;
}
#end
// usage:
UIWindow* w = [[TopWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
w.rootViewController = [UIViewController new];
w.hidden = NO;
[w.rootViewController presentViewController:yourActionSheetController animated:YES completion:nil];
This approach should be backwards compatible, but haven't tested all known versions. Happy hacking!
Based on Leo Natan's answer, I've created a Swift extension for presenting an alert sheet over the keyboard.
In my brief testing, the alertWindow is deallocated after the alert is dismissed, I believe because there's no strong reference to it outside of the alert. This means there's no need to hide or deallocate it in your UIAlertActions.
extension UIAlertController {
func presentOverKeyboard(animated: Bool, completion: (() -> Void)?) {
let alertWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
// If you need a white/hidden/other status bar, use an appropriate VC.
// You may not need a custom class, and you can just use UIViewController()
alertWindow.rootViewController = whiteStatusBarVC()
alertWindow.windowLevel = 10000001
alertWindow.hidden = false
// Set to a tint if you'd like
alertWindow.tintColor = UIColor.greenColor()
alertWindow.rootViewController?.presentViewController(self, animated: animated, completion: completion)
}
}
private class whiteStatusBarVC: UIViewController {
private override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
use UIAlertController instead of UIActionSheet

displaying Wiki mobile page in UIWebView within UIPopoverController

I try to open wiki mobile version webpage by a UIWebView within a UIPopoverController. the problem is, not matter how I set my contentSizeForViewInPopover, or just UIWebView frame, or simply set UIWebView.scalesPageToFit = YES. the Wiki mobile version page content size seem to larger than my UIWebView. But if I use it on iPhone, there's no such problem. here's my code for popover controller:
//create a UIWebView UIViewController first
WikiViewController *addView = [[WikiViewController alloc] init];
addView.contentSizeForViewInPopover = CGSizeMake(320.0, 480.0f);
//then create my UIPopoverController
popover = [[UIPopoverController alloc] initWithContentViewController:addView];
popover.delegate = self;
[addView release];
//then get the popover rect
CGPoint pointforPop = [self.mapView convertCoordinate:selectAnnotationCord
toPointToView:self.mapView];
CGRect askRect = CGRectMake((int)pointforPop.x, (int)pointforPop.y+10, 1.0, 1.0);
[popover presentPopoverFromRect:askRect
inView:self.mapView
permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];
[self.mapView deselectAnnotation:annotation animated:YES];
and this is my code on creating UIWebView:
- (void)viewDidLoad
{
wikiWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)];
wikiWebView.scalesPageToFit = YES;
//or No, doesn't matter, it all get larger than this
wikiWebView.delegate = self;
self.view = wikiWebView;
}
all code seem to be typical...
I wonder if anyone can shed me some light, thank you so much.
This is an enhanced version of auco answer, where if the viewport meta tag is not present it will be added:
- (void)webViewDidFinishLoad:(UIWebView*)webView
{
int webviewWidth = (NSUInteger)webView.frame.size.width;
if (!webView.loading) {
NSString *jsCmd = [NSString stringWithFormat:#"try {var viewport = document.querySelector('meta[name=viewport]');if (viewport != null) {viewport.setAttribute('content','width=%ipx, initial-scale=1.0, user-scalable=1');} else {var viewPortTag=document.createElement('meta');viewPortTag.id='viewport';viewPortTag.name = 'viewport';viewPortTag.content = 'width=%ipx, initial-scale=1.0, user-scalable=1';document.getElementsByTagName('head')[0].appendChild(viewPortTag);}} catch (e) {/*alert(e);*/}", webviewWidth, webviewWidth];
[webView stringByEvaluatingJavaScriptFromString:jsCmd];
}
}
Here is the Javascript pretty formatted code we are injecting in the WebView with a width of 320px
try {
var viewport = document.querySelector('meta[name=viewport]');
if (viewport != null) {
viewport.setAttribute('content',
'width=320px, initial-scale=1.0, user-scalable=1');
} else {
var viewPortTag = document.createElement('meta');
viewPortTag.id = 'viewport';
viewPortTag.name = 'viewport';
viewPortTag.content = 'width=320px,initial-scale=1.0, user-scalable=1';
document.getElementsByTagName('head')[0].appendChild(viewPortTag);
}
} catch (e) {
/*alert(e);*/
}
you can remove the try/catch if you want.
oh, i found in another QA that sometimes if html got a line "width=device-width", and you load a webview from popover controller, this popover controller will automatically send out device-width, not the view width you specified, and make your view ugly and funky. in that post it is a jQuery issue, and it solved with a jQuery way. In my problem, it is just a html issue in wiki mobile version. so I try another way, but similar.
I simple add a code in webViewdidload delegate method, first get URL html into a NSString, then use NSString instance method to search for "device-width" in loaded html, and replace it with my view width to make it a new NSString, then load this page with this new NSString. that's it.
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
if (!alreadyReload)
{
NSString *webHTML = [NSString stringWithContentsOfURL:webView.request.URL encoding:NSUTF8StringEncoding error:NULL];
NSRange range = [webHTML rangeOfString:#"device-width"];
if ((range.location!=NSNotFound)&&(range.length != 0))
{
webHTML = [webHTML stringByReplacingOccurrencesOfString:#"device-width" withString:#"whatever width you need" options:0 range:range];
[webView loadHTMLString:webHTML baseURL:wikiWebView.request.URL];
alreadyReload = YES;
}
}
}
something like this.
by the way, since I only use this on wiki mobile version, the html is simple and this kind of compare and replace is pretty easy. if you wanna use it in a more general case, you might use other way.
It would be much more efficient to manipulate the device-width via JavaScript rather than altering the html after it has fully loaded and then reloading the full page with modified html again.
This should work (and also consider if it's even necessary to change the viewport width):
- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
if(aWebView.frame.size.width < aWebView.window.frame.size.width) {
// width=device-width results in a wrong viewport dimension for webpages displayed in a popover
NSString *jsCmd = #"var viewport = document.querySelector('meta[name=viewport]');";
jsCmd = [jsCmd stringByAppendingFormat:#"viewport.setAttribute('content', 'width=%i, initial-scale=1.0, user-scalable=1');", (NSUInteger)aWebView.frame.size.width];
[aWebView stringByEvaluatingJavaScriptFromString:jsCmd];
}
// stop network indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

How to enable "select all" in UIWebView in an IPhone App?

I am writing an IPhone application which embeds a UIWebView. There are various safari like features like navigation, etc. One of the tasks I am looking for is to present a "select all" option when the user selects on a piece of text on the web view. Currently, I only see a "copy" option. Is there an easy way to enable the "select all" menu item? I have ofcourse tried adding a menu item to the shared menu controller but that doesn't necessarily implement the original safari "select all" functionality. Any help and pointers will be very useful.
Thanks in advance.
The short answer is no, this is not possible.
You could do this by subclassing UIWebView and overriding (without adding anythings to the menu controller yourself):
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender
And checking if the selector is selectAll:
Like this:
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender {
if (action == #selector(selectAll:)) {
return YES;
} else {
return [super canPerformAction:action withSender:sender];
}
}
This will show the Select All option on the Hold Menu. However this isn't default behaviour of a webView, and while the app won't crash when you press Select All, pressing it will just do nothing.
You can't even create a selectAll method, and then select everything in webview, because the javascript method .select() doesn't work on Mobile Safari/UIWebView.
You can implement selectAll behavior for non-editable webView (equivalent to behavior at Apple's Mail.app) at runtime using the following category for UIWebView.
The main idea is to use the hint that UIWebBrowserView being the subview of UIWebView is the subclass of UIWebDocumentView which conforms to UITextInputPrivate protocol which is equivalent to public UITextInput protocol
// UIWebView+SelectAll.h
// Created by Alexey Matveev on 28.03.15.
// Copyright (c) 2015 Alexey Matveev. All rights reserved.
#interface UIWebView (SelectAll)
+ (void)setEnableSelectAll:(BOOL)enabled;
#end
#import "UIWebView+SelectAll.h"
#import <objc/runtime.h>
/*
UIWebDocumentView is the superclass for UIWebBrowserView.
UIWebDocumentView conforms UITextInputPrivate protocol which is identival to UITextInput
*/
static IMP canPerformActionWithSenderImp;
#implementation UIWebView (SelectAll)
#dynamic enableSelectAll;
- (BOOL)customCanPerformAction:(SEL)action withSender:(id)sender
{
if (action == #selector(selectAll:)) {
return ! self.isSelectedAll;
}
else {
BOOL(*imp)(id, SEL, SEL, id) = (BOOL(*)(id, SEL, SEL, id))canPerformActionWithSenderImp;
return imp(self, #selector(canPerformAction:withSender:), action, sender);
}
}
- (void)selectAll:(id)sender
{
[self.browserView selectAll:sender];
}
- (UIView<UITextInput> *)browserView
{
UIView *browserView;
for (UIView *subview in self.scrollView.subviews) {
if ([subview isKindOfClass:NSClassFromString(#"UIWebBrowserView")]) {
browserView = subview;
break;
}
}
return (UIView<UITextInput> *)browserView;
}
- (BOOL)isSelectedAll
{
UITextRange *currentRange = self.browserView.selectedTextRange;
if ([self.browserView comparePosition:currentRange.start toPosition:self.browserView.beginningOfDocument] == NSOrderedSame) {
if ([self.browserView comparePosition:currentRange.end toPosition:self.browserView.endOfDocument] == NSOrderedSame) {
return YES;
}
}
return NO;
}
+ (void)setEnableSelectAll:(BOOL)enabled
{
SEL canPerformActionSelector = #selector(canPerformAction:withSender:);
if (!canPerformActionWithSenderImp) {
canPerformActionWithSenderImp = [self instanceMethodForSelector:canPerformActionSelector];
}
IMP newCanPerformActionWithSenderImp = enabled ? [self instanceMethodForSelector:#selector(customCanPerformAction:withSender:)] : canPerformActionWithSenderImp;
Method canPerformActionMethod = class_getInstanceMethod([self class], canPerformActionSelector);
class_replaceMethod([self class], canPerformActionSelector, newCanPerformActionWithSenderImp, method_getTypeEncoding(canPerformActionMethod));
}
#end
Of course, you can use global method swizzling for
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender;
in the standard way but it will affect all webViews in your project irreversably.

UISearchBar disable auto disable of cancel button

I have implemented a UISearchBar into a table view and almost everything is working except one small thing: When I enter text and then press the search button on the keyboard, the keyboard goes away, the search results are the only items shown in the table, the text stays in the UISearchBar, but the cancel button gets disabled.
I have been trying to get my list as close to the functionality of the Apple contacts app and when you press search in that app, it doesn't disable the cancel button.
When I looked in the UISearchBar header file, I noticed a flag for autoDisableCancelButton under the _searchBarFlags struct but it is private.
Is there something that I am missing when I setup the UISearchBar?
I found a solution. You can use this for-loop to loop over the subviews of the search bar and enable it when the search button is pressed on the keyboard.
for (UIView *possibleButton in searchBar.subviews)
{
if ([possibleButton isKindOfClass:[UIButton class]])
{
UIButton *cancelButton = (UIButton*)possibleButton;
cancelButton.enabled = YES;
break;
}
}
I had to tweak this a bit to get it work for me 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;
}
}
}
}
There is two way to achieve this easily
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
// The small and dirty
[(UIButton*)[searchBar valueForKey:#"_cancelButton"] setEnabled:YES];
// The long and safe
UIButton *cancelButton = [searchBar valueForKey:#"_cancelButton"];
if ([cancelButton respondsToSelector:#selector(setEnabled:)]) {
cancelButton.enabled = YES;
}
}
You should go with the second one, it will not crash your application if Apple will change it in the background.
BTW i tested it from iOS 4.0 to 8.2 and no changes, also i use it in my Store approved application without any issues.
This is what made it to work on iOS 6 for me:
searchBar.showsCancelButton = YES;
searchBar.showsScopeBar = YES;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:YES animated:YES];
Here's my solution, which works for all situations in all versions of iOS.
IE, other solutions don't handle when the keyboard gets dismissed because the user dragged a scroll view.
- (void)enableCancelButton:(UIView *)view {
if ([view isKindOfClass:[UIButton class]]) {
[(UIButton *)view setEnabled:YES];
} else {
for (UIView *subview in view.subviews) {
[self enableCancelButton:subview];
}
}
}
// This will handle whenever the text field is resigned non-programatically
// (IE, because it's set to resign when the scroll view is dragged in your storyboard.)
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
[self performSelector:#selector(enableCancelButton:) withObject:searchBar afterDelay:0.001];
}
// Also follow up every [searchBar resignFirstResponder];
// with [self enableCancelButton:searchBar];
As per my answer here, 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);
});
}
None of the answers worked for me at all. I'm targeting iOS 7. But I found an answer.
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).
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.
Here's a Swift 3 solution that makes use of extensions to get the cancel button easily:
extension UISearchBar {
var cancelButton: UIButton? {
for subView1 in subviews {
for subView2 in subView1.subviews {
if let cancelButton = subView2 as? UIButton {
return cancelButton
}
}
}
return nil
}
}
Now for the usage:
class MyTableViewController : UITableViewController, UISearchBarDelegate {
var searchBar = UISearchBar()
func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
tableView.tableHeaderView = searchBar
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
DispatchQueue.main.async {
if let cancelButton = searchBar.cancelButton {
cancelButton.isEnabled = true
cancelButton.isUserInteractionEnabled = true
}
}
}
}
For Monotouch or Xamarin iOS I have the following C# solution working for iOS 7 and iOS 8:
foreach(UIView view in searchBar.Subviews)
{
foreach(var subview in view.Subviews)
{
//Console.WriteLine(subview.GetType());
if(subview.GetType() == typeof(UIButton))
{
if(subview.RespondsToSelector(new Selector("setEnabled:")))
{
UIButton cancelButton = (UIButton)subview;
cancelButton.Enabled = true;
Console.WriteLine("enabledCancelButton");
return;
}
}
}
}
This answer is based on David Douglas solution.
A more complete answer:
since iOS 7, there is an additional level of subviews under the searchBar
a good place to enable the cancel button is in searchBarTextDidEndEditing
.
extension MyController: UISearchBarDelegate {
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
DispatchQueue.main.async {
// you need that since the disabling will
// happen after searchBarTextDidEndEditing is called
searchBar.subviews.forEach({ view in
view.subviews.forEach({ subview in
// ios 7+
if let cancelButton = subview as? UIButton {
cancelButton.isEnabled = true
cancelButton.isUserInteractionEnabled = true
return
}
})
// ios 7-
if let cancelButton = subview as? UIButton {
cancelButton.isEnabled = true
cancelButton.isUserInteractionEnabled = true
return
}
})
}
}
}
Time passes, but the problem is still there...
Elegant Swift 5/iOS 13 solution:
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
for case let cancelButton as UIButton in searchBar.subviews {
cancelButton.isEnabled = true
}
}

Resources