0

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Eduardo Urso
  • 296
  • 3
  • 6

2 Answers2

3

You can achieve this by setting the leftView of the searchField

if let textFieldInsideSearchBar = self.searchBar.valueForKey("searchField") as? UITextField {
   textFieldInsideSearchBar.leftView = imageView
}
iamszabo
  • 166
  • 2
  • 8
1

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
nivritgupta
  • 1,966
  • 2
  • 20
  • 38
  • 1
    Why do this? `UISearchBar` has an API for setting the icon and it is being used by the OP's code. – rmaddy Jul 24 '14 at 03:38
  • @maddy Yes i know that there is API Available - (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state but through this you can only set 4 types of UISearchBarIcon , There's no public API to change or remove that default icon , see Link http://stackoverflow.com/questions/13817330/how-to-change-inside-background-color-of-uisearchbar-component-on-ios – nivritgupta Jul 24 '14 at 05:38
  • Do you think this will fix my problem about the icon size? – Eduardo Urso Jul 24 '14 at 15:16
  • if you want to add custom , search icon in UISearch bar then yes – nivritgupta Jul 24 '14 at 17:26