Eduardo Urso
Eduardo Urso

Reputation: 296

How to change search icon inside UISearchBar?

I am trying to change the search icon inside an UISearchBar in iOS7 and ok, I got it. But is this the best way?

[self.searchBar setImage:[UIImage imageNamed: @"searchIcon.png"]
            forSearchBarIcon:UISearchBarIconSearch
                       state:UIControlStateNormal];

And the problem is that the image size is not great as the original, I would like to know the correct size to replace the image. I am using an image = 64x64 and an image@2x = 128x128, is it correctly? If so, why my search bar is like this:

SearchBar Icon Issue

Upvotes: 0

Views: 2930

Answers (2)

iamszabo
iamszabo

Reputation: 206

You can achieve this by setting the leftView of the searchField

if let textFieldInsideSearchBar = self.searchBar.valueForKey("searchField") as? UITextField {
   textFieldInsideSearchBar.leftView = imageView
}

Upvotes: 3

nivritgupta
nivritgupta

Reputation: 1966

to Replace the magnifying glass icon in an iPhone UISearchBar with a custom image use this code

#import <UIKit/UIKit.h>

@interface SearchBoxExperimentsViewController : UIViewController {
  IBOutlet UISearchBar *searchBar;
}

@end




#import "SearchBoxExperimentsViewController.h"

@interface SearchBoxExperimentsViewController (Private)
- (void)setSearchIconToFavicon;
@end


@implementation SearchBoxExperimentsViewController

- (void)viewDidLoad {
  [self setSearchIconToFavicon];
  [super viewDidLoad];
}

#pragma mark Private

- (void)setSearchIconToFavicon {
  // Really a UISearchBarTextField, but the header is private.
  UITextField *searchField = nil;
  for (UIView *subview in searchBar.subviews) {
    if ([subview isKindOfClass:[UITextField class]]) {
      searchField = (UITextField *)subview;
      break;
    }
  }

  if (searchField) {  
    UIImage *image = [UIImage imageNamed: @"favicon.png"];
    UIImageView *iView = [[UIImageView alloc] initWithImage:image];
    searchField.leftView = iView;
    [iView release];
  }  
}

@end

Upvotes: 1

Related Questions