Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable cancel button with UISearchBar in iOS8

Is there any method to enable 'Cancel' button of UISearchBar? Now whenever I call resignFirst responder, cancel button gets disabled. Only when I tap over the search bar again, cancel gets enabled. Is there anyway to stop disabling the cancel button?

like image 887
Advaith Avatar asked Dec 20 '22 09:12

Advaith


2 Answers

Here's a working solution for iOS 8 and Swift.

func enableCancleButton (searchBar : UISearchBar) {
    for view1 in searchBar.subviews {
        for view2 in view1.subviews {
            if view2.isKindOfClass(UIButton) {
                var button = view2 as! UIButton
                button.enabled = true
                button.userInteractionEnabled = true
            }
        }
    }
}
like image 175
Aaron Avatar answered Dec 21 '22 22:12

Aaron


For iOS7:

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

To make the above code work in iOS8, you need add a delay before enable the subview:

- (void)enableCancelButton{
    for (UIView *view in self.subviews){
        for (id subview in view.subviews){
            if ([subview isKindOfClass:[UIButton class]]){
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10), dispatch_get_main_queue(), ^{
                    [subview setEnabled:YES];
                });
                return;
            }
        }
    }
}
like image 43
Winter Avatar answered Dec 21 '22 22:12

Winter