Customizing search bar in iPhone application Development

10,724

Solution 1

you can subclass the UISearchBar and override the layoutSubviews method :

- (void)layoutSubviews {
   UITextField *searchField;
   NSUInteger numViews = [self.subviews count];
   for(int i = 0; i < numViews; i++) {
      if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform?
        searchField = [self.subviews objectAtIndex:i];
      }
   }
   if(!(searchField == nil)) {
       searchField.textColor = [UIColor whiteColor];
       [searchField setBackground: [UIImage imageNamed:@"yourImage.png"] ];
       [searchField setBorderStyle:UITextBorderStyleNone];
   }

   [super layoutSubviews];
}

Also you can :

//to clear searchbar backgraound
- (void) clearSearchBarBg
{
    for (UIView *subview in theSearchBar.subviews) 
    {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) 
        {
            [subview removeFromSuperview];
            break;
        }
    }
}

//display showSearchButtonInitially in a keyboard 
- (void)showSearchButtonInitially
{
    UIView * subview;
    NSArray * subviews = [theSearchBar subviews];

    for(subview in subviews)
    {
        if( [subview isKindOfClass:[UITextField class]] )
        {
            NSLog(@"setEnablesReturnKeyAutomatically");
            [((UITextField*)subview) setEnablesReturnKeyAutomatically:NO];
            ((UITextField*)subview).delegate=self;
            [((UITextField*)subview) setEnabled:TRUE];
            ((UITextField*)subview).borderStyle = UITextBorderStyleNone;
            break;
        }
    }
}

Solution 2

Look for Apple DOC for UISearchBar

enter image description here

You have bunch of methods there to get whatever you want

You can get UITextView Inside the search bar by

UITextField *textField = [searchBar.subviews objectAtIndex:2];

if ([textField isKindOfClass:[UITextField class]]) {
    //Do your customization
}

Again look for AppleDoc for UITextField. You have bunch of methods for that also.

Share:
10,724
Emon
Author by

Emon

Interest in programming and watching movie like illustionist,Brave heart,faceoff,Death race...etc.

Updated on June 24, 2022

Comments

  • Emon
    Emon almost 2 years

    In my application I have to add a search bar at the head of the tableview. I am able to add the searchbar but problem is without adding default search bar of ios can i add my customize search bar?? I am giving an image to see what types of search bar will be there...

    enter image description here