Jesper Martensson
Jesper Martensson

Reputation: 1248

UITextField within UISearchBar in iOS 7

I am trying to accomplish the same look of my UISearchBar with a TextField within it, as in my iOS 6 app. I have tried to code it in several ways and not yet been successful. The problem is, I am not able to change the TextField's frame in any way since iOS 7. The result is, my TextField takes all the space in the NavigationBar and overrides the UIBarButtonItem (menu button) to the right. See pictures below:

Screenshots

iOS 6 code: This is how I coded it in iOS 6, where I could set the TextFields frame to whatever I liked!

UITextField *sbTextField = (UITextField *)[searchBar.subviews lastObject];
[sbTextField removeFromSuperview];

CGRect rect = searchBar.frame;
rect.size.height = 32;
rect.size.width = 210;
sbTextField.frame = rect;

[sbTextField setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin];


UIBarButtonItem *searchBarNavigationItem = [[UIBarButtonItem alloc]  initWithCustomView:sbTextField];

[[self navigationItem] setLeftBarButtonItem:searchBarNavigationItem];

The result from the code above in iOS 7: ![iOS 7 look]

iOS 7 code: The difference in iOS 7, is that you need to use subViews in order to add the UITextField to the UISearchBar/UINavigationBar. By doing this I have not yet been able to change its frame. It currently overlaps the menuButton to the right which can be seen in the picture below this code...

UITextField* sbTextField;
CGRect rect = subView.frame;
rect.size.height = 32;
rect.size.width = 115;

for (UIView *subView in self.searchBar.subviews){
    for (UIView *ndLeveSubView in subView.subviews){

        if ([ndLeveSubView isKindOfClass:[UITextField class]])
        {

            sbTextField = (UITextField *)ndLeveSubView;
            sbTextField.backgroundColor =[UIColor whiteColor];
            UIBarButtonItem *searchBarNavigationItem = [[UIBarButtonItem alloc] initWithCustomView:sbTextField];
            sbTextField.frame = rect;
            self.navigationItem.leftBarButtonItem = searchBarNavigationItem;
            self.navigationItem.rightBarButtonItem =  menuButton;
            [sbTextField removeFromSuperview];

             break;
        }

    }

 }
 [self.searchBar reloadInputViews];

enter image description here SO...Is it possible to change a subView's frame (TextField) in any way ? :(

EDIT

The answer is kinda lame. In order to make the code work in ios7 with a button to the right of the TextField, the TextField must be set as the titleView of the navigationBar. Which was not the case in ios 6. But there will be other glitches and it is not recommended to use TextField within searchBars in iOS7. Use searchDispalyController instead. Se my answer below

 self.navigationItem.titleView = sbTextField;

Upvotes: 12

Views: 20926

Answers (7)

Tialtous
Tialtous

Reputation: 91

Swift solution

for subView in searchBar.subviews{
        for deeperView in subView.subviews{
            if let searchField:UITextField = deeperView as? UITextField{
                searchField.layer.borderWidth = 1.0
                searchField.layer.borderColor = UIColor(red: 134/255, green: 14/255, blue: 75/255, alpha: 1).CGColor
                searchField.layer.cornerRadius = 5.0
            }
        }
    }

Upvotes: 0

Adnan Aftab
Adnan Aftab

Reputation: 14487

in iOS 7 to access Text Field you have to reiterate on level more. Change your code like this

for (UIView *subView in self.searchBar.subviews){
    for (UIView *ndLeveSubView in subView.subviews){
    if ([ndLeveSubView isKindOfClass:[UITextField class]])
        {
            searchBarTextField = (UITextField *)ndLeveSubView;
            break;
        }
    }
   }

But best way to clear backgournd of UISearchBar and setting searchbar icon in text field is:

[searchBar setBackgroundImage:[[UIImage alloc] init] ];//if you want to remove background of uisearchbar
UIImage *image = [UIImage imageNamed: @"search_icon.png"];
[searchBar setImage:image forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

Upvotes: 13

Javier Querol
Javier Querol

Reputation: 1233

iOS6 & iOS7 compatible solution:

- (void)setTextFieldAsDelegate:(UIView *)inputView {
    for (UIView *view in inputView.subviews) {
        if ([view isKindOfClass:[UITextField class]]) {
            searchBarTextField = (UITextField *)view;
            searchBarTextField.delegate = self;
            break;
        } else {
            [self setTextFieldAsDelegate:view];
        }
    }
}

Upvotes: 2

Jesper Martensson
Jesper Martensson

Reputation: 1248

Thanx to spotdog13. I finally managed to make it work for iOS 7 properly in the following way:

#define TABLE_BOTTOM_MARGIN 5
#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize searchBar;
@synthesize searchResults;

- (void)viewDidLoad
{
 if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {


    [searchBar sizeToFit]; // standard size
    searchBar.delegate = self;

    // Add search bar to navigation bar
    self.navigationItem.titleView = searchBar;
    }
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
// Manually activate search mode
// Use animated=NO so we'll be able to immediately un-hide it again
[self.searchDisplayController setActive:YES animated:NO];
// Hand over control to UISearchDisplayController during the search
// searchBar.delegate = (id <UISearchBarDelegate>)self.searchDisplayController;

return YES;
}

#pragma mark <UISearchDisplayDelegate>
- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController
 // Un-hide the navigation bar that UISearchDisplayController hid
[self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController
                                           *)controller {
searchBar = (UISearchBar *)self.navigationItem.titleView;
// Manually resign search mode
[searchBar resignFirstResponder];
// Take back control of the search bar
searchBar.delegate = self;
}

Upvotes: -3

DiscDev
DiscDev

Reputation: 39052

You should not put a UITextField in the UINavigationBar in iOS 7, this widget is already provided by Apple.

In iOS 7, you can simply use a UISearchDisplayController with a UISearchBar, and set:

searchDisplayController.displaySearchBarInNavigationBar = YES

The search bar will appear in your UINavigationBar, and it will play nice with the other UIBarButtonItems without all the hacks and manual frame sizing in your original iOS 6 solution.

One thing to note - if you are going to add this to a project that still supports OSes older than iOS 7, you'll want to make sure that you put a check around the call or your app will crash when running on older OSes.

if([searchDisplayController respondsToSelector:@selector(displaysSearchBarInNavigationBar)])
{
    searchDisplayController.displaysSearchBarInNavigationBar = YES;
}

See this section of the iOS 7 transition guide: https://developer.apple.com/library/ios/documentation/userexperience/conceptual/TransitionGuide/Bars.html

In iOS 7, UISearchDisplayController includes the displaysSearchBarInNavigationBar property, which you can use to put a search bar in a navigation bar, similar to the one in Calendar on iPhone:

One other note - you should consider migrating to AutoLayout going forward so you don't have to do all that tedious frame manipulation. Apple recommends it, and probably for good reason (future devices with larger screens...?)

Upvotes: 13

Bhumit Mehta
Bhumit Mehta

Reputation: 16318

Try this out i am not sure but this should work as in iOS 7 searchbar has subview and inside that subview there are two subviews one of which is UITextField

UIView *searchbarview = [searchBar.subviews objectAtIndex:0];
UITextField *sbTextField = (UITextField *)[searchbarview.subviews lastObject];
[sbTextField removeFromSuperview];

CGRect rect = searchBar.frame;
rect.size.height = 32;
rect.size.width = 210;
sbTextField.frame = rect;

[sbTextField setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin];


UIBarButtonItem *searchBarNavigationItem = [[UIBarButtonItem alloc] initWithCustomView:sbTextField];

[[self navigationItem] setLeftBarButtonItem:searchBarNavigationItem];

Upvotes: 2

Syed Absar
Syed Absar

Reputation: 2284

Create a UIView *textFieldContainer with your target frame, add your textfield to that UIView and then add that textFieldContainer as a navigation item. i.e. your approach remains the same just the textfield comes inside a container and you play with that container.

Upvotes: 2

Related Questions