Related
Here, I'm trying to get the view of an accessoryButton in ios7.
My issue is similar to this one, but in a different version as I'm upgrading an ios 6 app to ios 7,
how can I retrieve detail disclosure buttons view
This work fine in ios 6, but it doesn't work in ios 7, I wonder why... here's my code:
- (UIView *)accessoryOfCell:(UITableViewCell *)tableViewCell
//Code inside method. I don't know how to quick indent so forget this {}
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0")) {
for (UIView *view in [tableViewCell subviews]) {
//this loop 1 times, return view has class UITableViewCellScrollView
for (UIView *subview in [view subviews]) {
//this loop 3 times, return subview as:
//UITableViewCellContentView, _UITableViewCellSeparatorView , UITableViewCellDetailDisclosureView
NSLog(#"%#", subview.class);
if ([view isKindOfClass:[UIButton class]]) {
return view;
}
}
}
}
else {
// in ios 6, this works super fine!
for (UIView *view in [tableViewCell subviews]) {
if ([view isKindOfClass:[UIButton class]]) {
return view;
}
}
}
return nil;
So with my code above won't return anything as UIButton in ios7.
NOTE: the "tableViewCell.accessoryView" return nil, I wonder why, since I choose detail disclosure in storyboard.
Any idea please?
EDIT NOTE:
I can as well put the code like this:
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0")) {
return ((UIView *)tableViewCell.subviews[0]).subviews[2];
} else { ... }
But I don't wanna, since this may cause update app in the future a pain in the #$$
EDIT NOTE #2:
This method is being called inside
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
...
}
In my application I am using search functionality using default IOS search bar, If i place some string for search its working fine but after the first search i need to display the entire data Source (original content) My functionality is if the search string is empty it will display the entire data source. My issue is if i make the search string as empty in default search bar, the search button automatically come to hide state. I need to enable the search button even the string is empty.
Actually you can just set searchBar.enablesReturnKeyAutomatically = NO; Tested on iOS 7+
This code display Search Button if you have empty string.
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[self.searchBar setShowsCancelButton:YES animated:YES];
self.tblView.allowsSelection = NO;
self.tblView.scrollEnabled = NO;
UITextField *searchBarTextField = nil;
for (UIView *subview in self.searchBar.subviews)
{
if ([subview isKindOfClass:[UITextField class]])
{
searchBarTextField = (UITextField *)subview;
break;
}
}
searchBarTextField.enablesReturnKeyAutomatically = NO;
}
Swift 3/ iOS 10
for view1 in searchBar.subviews {
for view2 in view1.subviews {
if let searchBarTextField = view2 as? UITextField {
searchBarTextField.enablesReturnKeyAutomatically = false
break
}
}
}
Use the following code for enable return key with no text
UITextField *searchField = nil;
for (UIView *subview in searchBar.subviews) {
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField *)subview;
break;
}
}
if (searchField) {
searchField.enablesReturnKeyAutomatically = NO;
}
Maybe is an apple side bug?. Since from the .xib file setting auto-enable return Key does not work as expected.
Just add the following code:
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
searchBar.enablesReturnKeyAutomatically = NO;
return YES;
}
Create a custom view & on that view add one button to remove the keyboard. Add that view when - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar delegate method of UISearchBar.
On that button click resign the keyboard as well as the view which you created for that button. Also if you want to search on that button click then you can do it as well.
Please see image for more clarification.
Its almost same as the accepted answer but if You are working with iOS 7 you will need extra for loop due to some changes in search bar
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[self.searchBar setShowsCancelButton:YES animated:YES];
UITextField *searchBarTextField = nil;
for (UIView *mainview in self.searchBar.subviews)
{
for (UIView *subview in mainview.subviews) {
if ([subview isKindOfClass:[UITextField class]])
{
searchBarTextField = (UITextField *)subview;
break;
}
}
}
searchBarTextField.enablesReturnKeyAutomatically = NO;
}
Use this it works for ios 6 and 7:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)search
{
UITextField *searchBarTextField = nil;
for (UIView *mainview in search.subviews) {
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
if ([mainview isKindOfClass:[UITextField class]]) {
searchBarTextField = (UITextField *)mainview;
break;
}
}
for (UIView *subview in mainview.subviews) {
if ([subview isKindOfClass:[UITextField class]]) {
searchBarTextField = (UITextField *)subview;
break;
}
}
}
searchBarTextField.enablesReturnKeyAutomatically = NO;
}
If you're looking for a bit more elegant solution, you could use recursion to find the textfield within the searchbar, as shown below. This should work for ios 6, 7, or any other future ios barring any deprecations by apple.
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
UITextField* textField = [self findTextFieldInView:searchBar];
if (textField) {
textField.enablesReturnKeyAutomatically = NO;
}
}
-(UITextField*)findTextFieldInView:(UIView*)view {
if ([view isKindOfClass:[UITextField class]]) {
return (UITextField*)view;
}
for (UIView* subview in view.subviews) {
UITextField* textField = [self findTextFieldInView:subview];
if (textField) {
return textField;
}
}
return nil;
}
Simple Swift version:
if let searchTextField:UITextField = searchBar.subviews[0].subviews[2] as? UITextField {
searchTextField.enablesReturnKeyAutomatically = false
}
Here is a solution using Swift. Just paste it in your viewDidLoad function and make sure that you have an IBOutlet of your searchBar in the code. (on my example below, the inputSearchBar variable is the IBOutlet)
// making the search button available when the search text is empty
var searchBarTextField : UITextField!
for view1 in inputSearchBar.subviews {
for view2 in view1.subviews {
if view2.isKindOfClass(UITextField) {
searchBarTextField = view2 as UITextField
searchBarTextField.enablesReturnKeyAutomatically = false
break
}
}
}
In swift use UISearchBarDelegate
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.enablesReturnKeyAutomatically = false
}`
In iOS6 in the methods viewControllerAfterViewController and viewControllerBeforeViewController if I return nil (for block the page navigation when I am in the first or last page) the app crash with this exception:
'The number of view controllers provided (0) doesn't match the number required (1) for the requested transition'
In iOS5 all works good.
I had the same issue. I found that the cause was replacing the delegate on the UIPanGestureRecognizer of the UIPageViewController, a no-no really. The pan gesture recognizer was calling an undocumented method _gestureRecognizerShouldBegin: (note the leading underscore) that UIPageViewController implements and apparently relies upon to work properly (read: not-crash). I ended up implementing respondsToSelector: and forwardingTargetForSelector: in my class that uses the UIPageViewController to pass the undocumented delegate method on to the UIPageViewController without specifically naming it (and almost certainly earning me an app store review rejection).
-(BOOL)respondsToSelector:(SEL)aSelector {
if ([super respondsToSelector:aSelector])
return YES;
else if ([self.pageViewController respondsToSelector:aSelector])
return YES;
else
return NO;
}
- (id)forwardingTargetForSelector:(SEL)aSelector {
if ([super respondsToSelector:aSelector]) {
return nil;
} else if ([self.pageViewController respondsToSelector:aSelector]) {
return self.pageViewController;
}
return nil;
}
My longer term solution will be to rework the use of UIPageViewController such that I don't need to displace the gesture recognizer delegates.
Ah,was wondering why no one has pointed out this bug,which i took almost 2 nights to find out the solution.
OLD CODE(iOS 5.1) : when returning nil on the first and last page you will experience the app crash.It works fine in iOS 5.1,but in iOS 6 it wont.
- (UIViewController *)pageViewController:
(UIPageViewController *)pageViewController viewControllerBeforeViewController:
(UIViewController *)viewController
{
for (UIGestureRecognizer *recognizer in pageController.gestureRecognizers) {
if ([recognizer isKindOfClass:[UITapGestureRecognizer class]]) {
recognizer.enabled = NO;
}
}
NSUInteger index = [self indexOfViewController:
(MainViewController *)viewController];
if ((index == 0) || (index == NSNotFound)) {
return nil;
}
index--;
return [self viewControllerAtIndex:index];
}
- (UIViewController *)pageViewController:
(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
for (UIGestureRecognizer *recognizer in pageController.gestureRecognizers) {
if ([recognizer isKindOfClass:[UITapGestureRecognizer class]]) {
recognizer.enabled = NO;
}
}
NSUInteger index = [self indexOfViewController:
(MainViewController *)viewController];
if (index == NSNotFound) {
return nil;
}
}
SOLUTION(iOS 6) : After adding the gesture effect to the superview,just call the delegate called -(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer. What i did is quiet simple, computing the speed of the user flipping the first page and last page (i mean using the gesture recognizer) , i denied the swiping.All you need to do is just paste the following code,and you are DONE!.
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
if (pageNum==0) {
if ([(UIPanGestureRecognizer*)gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] &&
[(UIPanGestureRecognizer*)gestureRecognizer velocityInView:gestureRecognizer.view].x > 0.0f) {
//NSLog(#"Swiping to left on 1st page is denied");
return NO;
}
if ([(UITapGestureRecognizer*)gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]] &&
[(UITapGestureRecognizer*)gestureRecognizer locationInView:gestureRecognizer.view].x < self.view.frame.size.width/2) {
//NSLog(#"tapping to left on 1st page is denied");
return NO;
}
}
else if(pageNum ==totalNoOfFiles-1)
{
if ([(UIPanGestureRecognizer*)gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] &&
[(UIPanGestureRecognizer*)gestureRecognizer velocityInView:gestureRecognizer.view].x < 0.0f) {
//NSLog(#"Swiping to right on 1st page is denied");
return NO;
}
if ([(UITapGestureRecognizer*)gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]] &&
[(UITapGestureRecognizer*)gestureRecognizer locationInView:gestureRecognizer.view].x > self.view.frame.size.width/2) {
//NSLog(#"Tapping to right on 1st page is denied");
return NO;
}
}
return YES;
}
- (UIViewController *)pageViewController:(UIPageViewController*) pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
int index = [self indexOfViewController:(ChildViewController *)viewController];
index--;
return [self viewControllerAtIndex:index];
}
- (UIViewController *)pageViewController:
(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
int index = [self indexOfViewController:(ChildViewController *)viewController];
index++;
return [self viewControllerAtIndex:index];
}
This has been well discussed but I have one thing to add. Consider why you were setting the delegate of the gesture recognizers to self. In my case, it was because in some cases I wanted to prevent the gesture recognizers from recognizing, with the delegate's gestureRecognizerShouldBegin:.
But in iOS 6, where this issue arises, there is a whole new way of doing exactly that, by implementing gestureRecognizerShouldBegin: on a UIView. (This is a new UIView instance method in iOS 6.)
Thus I was able to accomplish exactly what I was accomplishing before, without altering the gesture recognizers' delegate.
I had the issue with UIPageViewController crashing with iOS6 with the same error ('The number of view controllers provided (0) doesn't match the number required (1) for the requested transition').
None of the above solutions worked for me but I eventually found that moving the following line from viewDidLoad to viewDidAppear fixed it.
self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
Totally same issue here.
What I did was a hotfix which just to returns clone of before/afterViewController instead of nil, i.e.
// viewController = before/afterViewController
NSUInteger index = [self indexOfViewController:viewController];
// NOTE: return nil crashes in iOS6
return [self viewControllerAtIndex:index storyboard:viewController.storyboard];
This means you can page-curl forever but I had no other choice...
Better solution is always welcome.
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.
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.)
try this
for(id subview in [yourSearchBar subviews])
{
if ([subview isKindOfClass:[UIButton class]]) {
[subview setEnabled:YES];
}
}
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;
}
}
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.
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.
You can use the runtime API to access the cancel button.
UIButton *btnCancel = [self.searchBar valueForKey:#"_cancelButton"];
[btnCancel setEnabled:YES];
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
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.
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
}
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).
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.
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
}
}
}
}
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
}
}
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.
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
}
}
}
For iOS 9/10 (tested), Swift 3 (shorter):
searchBar.subviews.flatMap({$0.subviews}).forEach({ ($0 as? UIButton)?.isEnabled = true })
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()
}
for (UIView *firstView in searchBar.subviews) {
for(UIView* view in firstView.subviews) {
if([view isKindOfClass:[UIButton class]]) {
UIButton* button = (UIButton*) view;
[button setEnabled:YES];
}
}
}
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);
}
}
A better solution is
[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil].enabled = YES;
Better & Easy method:
[(UIButton *)[self.searchBar valueForKey:#"_cancelButton"] setEnabled:YES];
Swift 5 & iOS 14
if let cancelButton : UIButton = self.menuSearchBar.value(forKey: "cancelButton") as? UIButton {
cancelButton.isEnabled = true
}
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.)
I am using a UISearchBar to match text input against entries in a database and display the matched results to the user in a UITableView, as they type.
All is well, however, I cannot find a way to alter the return key type of the search bar's keyboard. By default it replaces the standard return key with a Search button. Because I am doing a live search as the user types, I do not need this button and having it there and inactive has raised some usability issues.
Attempted solutions
I can set a keyboard with the setKeyboard:UIKeyboardType method, however this doesn't seem to override the default setting of replacing the return key (on the standard keyboard) with a Search key and it does not allow access to change this return key.
I have thought about using a UITextField, giving me access to the returnKeyType property through the UITextInputTraits protocol. My problem with this however is that I am implementing the UISearchBarDelegate method searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText, which I would lose with the UITextField.
Is there a way that I can keep the functionality of the search bar's delegate methods, whilst having legitimate access to the keyboard's return key?
In fact, almost the exact screen I am implementing is found in Apple's Clock application
Screenshot:
So any help on a clean solution would be much appreciated. Note the return key on the bottom right instead of the default Search button'.
Slightly different in iOS 7 compared to the answer of #sudip.
for (UIView *subview in self.searchBar.subviews)
{
for (UIView *subSubview in subview.subviews)
{
if ([subSubview conformsToProtocol:#protocol(UITextInputTraits)])
{
UITextField *textField = (UITextField *)subSubview;
[textField setKeyboardAppearance: UIKeyboardAppearanceAlert];
textField.returnKeyType = UIReturnKeyDone;
break;
}
}
}
I tried all of these solutions without luck until I realized that in IOS8, you can just set searchBar.returnKey = .Done or whatever UIReturnKeyType you like. Sigh.
Try this:
for(UIView *subView in searchBar.subviews) {
if([subView conformsToProtocol:#protocol(UITextInputTraits)]) {
[(UITextField *)subView setKeyboardAppearance: UIKeyboardAppearanceAlert];
}
}
If you want to dismiss the return key (i.e., make it do nothing), set the "returnKeyType" property on the UITextField subview to "UIReturnKeyDone" along with "keyboardAppearence".
I had to add some lines to Neo's answer. Here is my code to add a "Done" button for UISearchbar :
for(UIView *subView in sb_manSearch.subviews) {
if([subView conformsToProtocol:#protocol(UITextInputTraits)]) {
UITextField *t = (UITextField *)subView;
[t setKeyboardAppearance: UIKeyboardAppearanceAlert];
t.returnKeyType = UIReturnKeyDone;
t.delegate = self;
break;
}
}
To change Search into Done text.
Use below code.
youtSearchBar.returnKeyType = .done
you can do it by :
- (void)viewDidLoad
{
// Adding observer that will tell you keyboard is appeared.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification object:nil];
[super viewDidLoad];
}
- (void)keyboardDidShow:(NSNotification *)note
{
keyboardTest = [self getKeyboard];
[keyboardTest setReturnKeyEnabled: YES];
}
- (id) getKeyboard // Method that returns appeared keyboard's reference
{
id keyboardView;
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++)
{
keyboard = [tempWindow.subviews objectAtIndex:i];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2)
{
if([[keyboard description] hasPrefix:#"<UIPeripheralHost"] == YES)
{
keyboard = [[keyboard subviews] objectAtIndex:0];
keyboardView = keyboard ;
}
}
else
{
if([[keyboard description] hasPrefix:#"<UIKeyboard"] == YES)
keyboardView = keyboard ;
}
}
return keyboardView ;
}
UPDATE : From iOS 7 onwards, the accepted answer will not work, below version will the work on iOS 7 onwards.
UIView *subViews = [[_searchBar subviews] firstObject];
for(UIView *subView in [subViews subviews]) {
if([subView conformsToProtocol:#protocol(UITextInputTraits)]) {
[(UITextField *)subView setEnablesReturnKeyAutomatically:NO];
}
}
for (UIView *subView in view.subviews) {
if ([subView isKindOfClass:[UITextField class]])
{
UITextField *txt = (UITextField *)subView;
#try {
[txt setReturnKeyType:UIReturnKeyDone];
[txt setKeyboardAppearance:UIKeyboardAppearanceAlert];
}
#catch (NSException * e) {
// ignore exception
}
}
}
I just found the simplest wait to hack this, just put a blank when beginning editing search field
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
//Add a blank character to hack search button enable
searchBar.text = #" ";}