iphone UISearchBar Done button always enabled
You can get around this by looping around the subviews in the UISearchBar until you find the text field. Its then just a matter of setting "enablesReturnKeyAutomatically" to NO. Incidentally the following code also is useful for setting the keyboard type.
// loop around subviews of UISearchBar
for (UIView *searchBarSubview in [searchBar subviews]) {
if ([searchBarSubview conformsToProtocol:@protocol(UITextInputTraits)]) {
@try {
// set style of keyboard
[(UITextField *)searchBarSubview setKeyboardAppearance:UIKeyboardAppearanceAlert];
// always force return key to be enabled
[(UITextField *)searchBarSubview setEnablesReturnKeyAutomatically:NO];
}
@catch (NSException * e) {
// ignore exception
}
}
}
The accepted answer doesn't seem to work anymore, so I made my own category that does seem to work:
@implementation UISearchBar (enabler)
- (void) alwaysEnableSearch {
// loop around subviews of UISearchBar
NSMutableSet *viewsToCheck = [NSMutableSet setWithArray:[self subviews]];
while ([viewsToCheck count] > 0) {
UIView *searchBarSubview = [viewsToCheck anyObject];
[viewsToCheck addObjectsFromArray:searchBarSubview.subviews];
[viewsToCheck removeObject:searchBarSubview];
if ([searchBarSubview conformsToProtocol:@protocol(UITextInputTraits)]) {
@try {
// always force return key to be enabled
[(UITextField *)searchBarSubview setEnablesReturnKeyAutomatically:NO];
}
@catch (NSException * e) {
// ignore exception
}
}
}
}
Nowadays UISearchBar
conforms to UITextInputTraits
. You can simply set:
searchBar.enablesReturnKeyAutomatically = NO;
WARNING: While this compiles for iOS 7.0, it will crash at runtime. It only works for >=7.1.
The docs are not clear on this one, as only since 7.1, the UISearchBar
implements the UITextInputTraits
protocol, but it is not noted since which iOS version the protocol is adopted.