30

I have a UITableView with an Index on the side; I want to add a UISearchBar to it, but the index overlaps with the "x" to clear the search. I've noticed in the Contacts application, the textfield within the UISearchBar is resized to accommodate this, but I can't work out how to do this in my own app.

I have tried the following in my viewDidLoad, but it does not seem to work.

UITextField * textField = (UITextField *)[[self.search subviews] objectAtIndex:0];
CGRect r = textField.frame;

[textField setFrame:CGRectMake(r.origin.x, r.origin.y, r.size.height, r.size.width-30)];

Any ideas?

Padraig
  • 1,569
  • 2
  • 15
  • 21

18 Answers18

30

it's much easier than all these suggestions. In interface builder, instead of putting the Search Bar as the header of your Table View, you can put a View instead. Then, put a Navigation Bar inside this View. Grab the left resizing handle of the Navigation Bar and pull it to the right until the N B is only 25 pixels wide. Clear out the Title in the N B (double click to select it, then delete). Then, add a Search Bar into the same View. Move its right resizing handle to the left, adjust so that it abuts the N B. That's it.

You can enable a cancel button if you want too and it also won't overlap the index (remains within the search bar).

Apparently a Table View can only have 1 subview in its header, that's why you need to put the View first, then the N B and Search Bar inside it.

UPDATE: see Beginning iPhone Development from Apress, p. 241 of SDK 3 edition. You just disable the index while searching.

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (isSearching) {
        return nil;
    }
    return keys;
}

Also they talk about adding a magnifying glass to the top of the index.

Great book all around.

Mike
  • 316
  • 3
  • 3
  • Worked great - one addition - our table view has some custom style applied to it and to get the Navigation Bar and the Search Bar to look the same I had to make the parent View transparent (i.e. no background) - so if things don't quite match try this. – Joe May 12 '10 at 15:38
  • Brilliant. Just pure brilliance. Thanks! – hishamaus Jul 29 '13 at 00:15
16

Why not just make the actual UISearchBar smaller horizontally, and place an (empty) UINavigationBar to the right of it? They will render the exact same background.

Better than hacking the internals of Apple's objects that could change.

Also, when animating the UISearchBar's width, you'll notice that the inner text field is not animated along with it. You can fix this by calling UISearchBar's "layoutSubviews" within your animation block after changing its frame. (that's where it determines the size of the inner text field)

Nick Farina
  • 4,470
  • 2
  • 32
  • 30
  • Thank you so much man!!!! I couldn't figure out how to get the searchbar to animate. layoutSubviews was the key. – Meroon Nov 04 '09 at 19:18
  • I had a UISearchBar on the right-hand-side of a UINavigationBar and animate it in and out, just like the Safari app. This tip to layoutSubview of UISearchBar was the final piece of the puzzle to get it working just like Safari. No need to search subviews, or anything like that, which isn't the right or clean solution. Thanks again for the right answer. – petert Jun 18 '10 at 08:19
  • This also solved the problem for me in an easy and clean way. Thanks! – David Coufal Jul 02 '10 at 22:11
8

Ok, I've come up with a solution.

  1. Create a subclass of UISearchBar
  2. Include this code in the drawRect: method.

    UITextView * textField = [self.subviews objectAtIndex:0];
    textField.frame = CGRectMake(5, 6, (310 - kRightSideMargin), 31); 
    
    [super drawRect:rect];
    

Note: kRightSideMargin is a constant I set in my header file; I have it set to 25.

Thanks for the suggestions from everyone else.

Padraig
  • 1,569
  • 2
  • 15
  • 21
  • 2
    Im using v3.0 iphone SDK and placing this code in drawRect did not work. What actually worked for me was placing this code in layoutSubviews. Not exactly sure why - the only conclusion i can draw is that there's a change in v2 -> v3 – CVertex Aug 09 '09 at 05:09
6

As of iOS 6, the navigation bar solution didn't work well for me because of slightly different looks now between the UISearchBar and UINavigationBar. So, I switched to something similar to Padraig's approach by subclassing the UISearchBar.

@interface SearchBarWithPad : UISearchBar
@end


@implementation SearchBarWithPad
- (void) layoutSubviews {

    [super layoutSubviews];
    NSInteger pad = 50;
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass: [UITextField class]])
        view.frame = CGRectMake (view.frame.origin.x, view.frame.origin.y, view.frame.size.width - pad, view.frame.size.height);
    }   
}
@end

Edit: Ah, I haven't tried it, but I think you might be able to set a navigation bar's clipToBounds = YES to turn off it's new shadow, thereby creating a consistent look again between the two controls.

Ernie Thomason
  • 1,579
  • 17
  • 20
  • 1
    This doesn't quite work with iOS 7... self.subviews now consists of a single UIView, which in turns holds the UITextField we're looking for. So for iOS 7, you can do something like UIView *topView = [self.subviews objectAtIndex: 0]; then iterate through topView.subviews just like above to make this work. – Ernie Thomason Jul 19 '13 at 04:02
6

As Padraig pointed out all you have to do is subclass out the searchBar. Create your UISearchBar subclass, and add the following code into the layoutSubviews method:

- (void)layoutSubviews
{
    UITextField *searchField;

    for(int i = 0; i < [self.subviews count]; i++)
    {
        if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]])
        {
            searchField = [self.subviews objectAtIndex:i];
        }
    }

    if(!(searchField == nil))
    {
        searchField.frame = CGRectMake(4, 5, 285, 30); 
    }
}

This loops through all the subviews and checks them against type UITextField. That way if it ever moves in its line up of subviews this will still grab it. I found 285 to just wide enough not to overlap with the index of my tableView.

  • 1
    This doesnt work. Where should I add method? In .h or .m? Note: Change to ...; int i = 0; if (i ; i<[self.subviews count]; i++) { – wagashi Sep 28 '11 at 10:34
5

I am using ViewDeck and want to show a UISearchbar inside the leftController.

Now the problem is if I open the left side which contains the navigation, the right bit overlaps my search field.

I got rid of this by over writing UISearchBar, the textfield will always have the same width, but in one case there is the ViewDeck overlapping and in the other case I hide the ViewDeck-bit and then the cancel button will take up the space:

Subclassing UISearchBar

#import "ViewDeckSearchBar.h"
#define kViewDeckPadding 55

@interface ViewDeckSearchBar()
@property (readonly) UITextField *textField;
@end

@implementation ViewDeckSearchBar

static CGRect initialTextFieldFrame;

- (void) layoutSubviews {

    [super layoutSubviews];

    // Store the initial frame for the the text field
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        initialTextFieldFrame = self.textField.frame;
    });

    [self updateTextFieldFrame];
}

-(void)updateTextFieldFrame{

    int width = initialTextFieldFrame.size.width - (kViewDeckPadding + 6);
    CGRect newFrame = CGRectMake (self.textField.frame.origin.x,
                                  self.textField.frame.origin.y,
                                  width,
                                  self.textField.frame.size.height);

    self.textField.frame = newFrame;
}

-(UITextField *)textField{
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass: [UITextField class]]){
            return (UITextField *)view;
        }
    }

    return nil;
}

@end

ViewController class

In my Navigation class I need to overwrite these two UISearchbarDelegate methods in order to go to fullscreen with the search results:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{

    [self.viewDeckController setLeftSize:0];

    // I am also using scopes, which works fine (they fade out when not searching)
    self.searchBar.scopeButtonTitles = @[@"Food",
                                         @"Beverages",
                                         @"Misc"];
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    self.viewDeckController.leftSize = 55;
}

Result

ViewDeck showing to the right:

a
(source: minus.com)

Search in Fullscreen (The button and the scope buttons are animated in).

a
(source: minus.com)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Besi
  • 22,579
  • 24
  • 131
  • 223
  • For iOS 7 and 8 you have to change the textField method: -(UITextField *)textField{ UIView *topView = [self.subviews objectAtIndex: 0]; for (UIView *view in topView.subviews) {... – Ricardo Nov 14 '14 at 10:58
4
searchBar.layoutMargins = UIEdgeInsetsMake(0, 0, 0, rightPad);

My old solution of changing the UITextField frame stopped working in iOS 13. Putting a UINavigationBar to the right of the UISearchBar never worked well for me as they had different looks at top and bottom.

Ernie Thomason
  • 1,579
  • 17
  • 20
2

Sorry to drag this all up again.

I wanted the UISearchBar to be shorter, and I'm using a UISearchBarController, but without actually wanting the index. This is because I have an overlay to the right:

Long search bar

To do this, I fake a sectionIndex with one blank item, then hide it. Here's how I do that:

 - (void)hideTableIndex {
    for (UIView *view in [tableView subviews]) {
        if ([view isKindOfClass:NSClassFromString(@"UITableViewIndex")]) {
            view.hidden = YES;
        }
    }
 }

 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)aTableView {
    if (aTableView == self.searchDisplayController.searchResultsTableView) {
        return nil;
    } else {
        [self performSelector:@selector(hideTableIndex) withObject:nil afterDelay:0];
        return [NSArray arrayWithObjects:@"", nil];
    }
 }

 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return 0;
 }

This shortens the the UISearchBar and hides the index so it can't be tapped (a small section would otherwise hand to the left of the overlay that when tapped would scroll the UITableView to the top). Like this:

alt text

Best of all, when you use the search, you still get the full width bar:

alt text

Alastair Stuart
  • 4,165
  • 3
  • 36
  • 33
2

Just put a UIView and put the search bar inside that UIView. UIView must be of same size as UISearchBar. this worked for me.

Ideveloper
  • 1,467
  • 4
  • 23
  • 44
  • hey, how to add the searchbar into a UIView on the current frame? I tried it, but the searchbar is behind of that added UIView..thanks! – trillions Feb 28 '13 at 10:38
1

Sorry for Necroposting, but I found another way to make a little space on the right of the textfield. I was having the problem, that I had an indexed tableview with a searchbar as the first row. Now the index and the searchbar (made in IB, btw.) were overlapping. It tried almost everything with no success. It seems that the width and height properties of the textifield don't respond... So I came up with this:

searchBar.showsCancelButton = YES;

UIView *cButton = [searchBar.subviews objectAtIndex:2];

cButton.hidden = YES;

I still can't adjust the size of the space, but this does it for now... although... pretty weird solution...

1

Everyone has provided ways to modify the UI. I have discovered how to obtain identical results. You must provide the following two implementations:

  1. Use UISearchDisplayController More importantly, make sure you initialize it with:

- (id)initWithSearchBar:(UISearchBar *)searchBar contentsController:(UIViewController *)viewController

Failure to set a valid UISearchBar (or passing nil) will prevent the adjustment of the UITextField for the index.

  1. You must return a valid array of titles by implementing:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;

If you return nil, the index will not be displayed, and the UITextField will not be properly adjusted.

I've submitted a bug report to Apple, suggesting that it seems logical that only #2 should be required, not #1. I have found nothing in the Human Interface Guideline (iPhone HIG) requiring use of the UISearchDisplayController.

Mark
  • 556
  • 8
  • 12
  • I used the IB search display controller — which I think implements `-initWithSearchBar:contentsController:` — and this worked to resize the search bar field. – Alex Reynolds Apr 29 '10 at 08:22
1

The key is to use the "Search Bar and Search Display Controller" and not the "Search Bar" when using Interface Builder.

1

The text field used in UISearchBar is a subclass of UITextField called UISearchBarTextField.

AFAIK, there's no way to resize a UISearchBarTextField using the public API, and the private API doesn't reveal much either.

Maybe you can take a look at UISearchBarTextField's subviews, if it has any.

UPDATE: It doesn't.

UPDATE 2: I think you should take a look at UITextField's rightView property. The below code, although it doesn't work, seems like a good starting point:

UIView *emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
[textField setRightView:emptyView];
[textField setRightViewMode:UITextFieldViewModeAlways];
[emptyView release];
Can Berk Güder
  • 109,922
  • 25
  • 130
  • 137
  • Looks like you could bluff it that way by sticking an image on top of it. Add the line: emptyView.backgroundColor = [UIColor blackColor]; into your code to see how it would work. – Padraig Feb 17 '09 at 14:31
0

Another appraoch (though tedious) would be to resize the search bar and fill the 'gap' with a navigation bar. Works for me.

Bart Jacobs
  • 9,022
  • 7
  • 47
  • 88
0

What I've come up with isn't too much better. Basically, I make an empty view with the frame that I want to use for the search bar. Then I create a UIToolbar to go behind the search bar. Be sure to set its frame to the same frame as the UIView, except that the Y value has to be -1; otherwise, you'll get two borders drawn at the top. Next create your UISearchBar, but set the frame's width to 30 (or whatever makes sense for your app) less than the UIView. Add them as subviews and set your UIView as the tableHeaderView.

Jeff Kelley
  • 19,021
  • 6
  • 70
  • 80
0

I followed Mike's advice by making a UIView, then putting a Navigation Bar and UISearch Bar inside it. Only problem is first time the search bar is shown its background is the same as a Navigation Bar normally?

Interestingly, if I activate the search, then click cancel the background of this 'fixed'!?

I'm using SDK 3.0, so I removed the UISearchBar item made when I dragged a UISearchDisplayController in to my NIB, then made the view as described above and wired it up to the file owner and the searchBar outlet in the search display controller.

petert
  • 6,672
  • 3
  • 38
  • 46
0

It work fine!!!

[searchBar setContentInset:UIEdgeInsetsMake(5, 0, 5, 35)];

Oscar
  • 49
  • 1
  • 1
  • I like this, cos it's not supposing that the object index is 0, or 2. Which means I don't need to test this specifically and change every single SDK upgrade... – boymc Feb 14 '11 at 04:57
  • I think this way will be easy and acceptable , but I think that Apple should fix this problem because obviously it should be adjust the position of the left index title bar if something was show on the heardview of the table view. anyway, I use this way now, thanks for oscar and all :) – iXcoder Apr 02 '11 at 04:45
  • 21
    NOTE: `UISearchBar` doesn't respond to `setContentInset` – joshpaul Sep 22 '11 at 14:59
  • Yes... Private API stuff could well get your app rejected. – jowie Oct 07 '11 at 15:54
0

It kind of looks as though Apple resize the view (note that the index is animated to the right, off screen), making it bigger than the screen.

I would imagine that you'd need to implement the searchBarTextDidBeginEditing: method of the UISearchBarDelegate to trigger this at the appropriate point. This does, however, feel a bit hacky do maybe there's a better way of doing it.

Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152
  • Thanks Stephen. I'm interested in getting the initial UISearchBar textfield to be smaller from the start. There are some other threads about the index animation, but that's not what I'm trying to work out right now. – Padraig Feb 17 '09 at 14:24