Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom clear button in UISearchBar text field

I tried:

UITextField *searchtextfield = [searchBar.subviews objectAtIndex:1];
    UIButton *cButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cButton.frame = CGRectMake(0, 0, 20 , 20);
    cButton.backgroundColor = [UIColor clearColor];
    [cButton setImage:[UIImage imageNamed:@"x-button"] forState:UIControlStateNormal];//your button image.
    cButton.contentMode = UIViewContentModeScaleToFill;
    [cButton addTarget:self action:@selector(xButtonPressed) forControlEvents:UIControlEventTouchUpInside];//This is the custom event
    [searchtextfield setRightView:cButton];
    [searchtextfield setRightViewMode:UITextFieldViewModeWhileEditing];

But it doesn't work very well... It displays custom button, but when you type something, the old one get's back...

How can I do this?

like image 834
1337code Avatar asked Dec 13 '12 14:12

1337code


2 Answers

If you want to set a custom clear button in a UISearchBar try this:

[[UISearchBar appearance] setImage:[UIImage imageNamed:@"MyClearButton.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];

Don't forget to set an image for UIControlStateHighlighted

[[UISearchBar appearance] setImage:[UIImage imageNamed:@"HighlightedClearButton.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
like image 156
irblue Avatar answered Sep 26 '22 23:09

irblue


You need the following

[searchBar setImage:[UIImage imageNamed:@"image1"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
[searchBar setImage:[UIImage imageNamed:@"image2"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];

It is strongly recommended to place strings in this order starting from UIControlStateHighlighted in case you want to use the same image: image1=image2=image.

In iOS7 it is weird but fact that direct order of UIControlStateNormal and UIControlStateHighlighted doesn't work.

like image 39
malex Avatar answered Sep 24 '22 23:09

malex