Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change UISearchBar textfield background color and text color in ios8

I used below code for changing UISearchBar textfield background color.

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{
                                                                   NSForegroundColorAttributeName : [UIColor redColor],
                                                                     NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                            }];

but it does not work for me, can any one give solution. thanks in advance

like image 669
Vishnu Avatar asked Oct 06 '15 11:10

Vishnu


2 Answers

Try this:

UITextField *searchField = [self.searchBar valueForKey:@"searchField"];

// To change background color
searchField.backgroundColor = [UIColor blueColor];

// To change text color
searchField.textColor = [UIColor redColor];

// To change placeholder text color
searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Some Text"];
UILabel *placeholderLabel = [searchField valueForKey:@"placeholderLabel"];
placeholderLabel.textColor = [UIColor grayColor];
like image 179
Abhinav Avatar answered Oct 12 '22 19:10

Abhinav


Just try this code

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]];

OR

Try this

- (void)viewDidLoad
    {
        [super viewDidLoad];

        //change the background color

 [[self searchViewForTextFieldBg:self.searchTextfield] setBackgroundColor:[UIColor grayColor]];

//change the textcolor
self.searchTextfield.textColor =[UIColor greenColor];

    }

    - (UITextField*)searchViewForTextFieldBg:(UIView*)view
{
    if ([view isKindOfClass:[UITextField class]]) {
        return (UITextField*)view;
    }
    UITextField *searchTextField;
    for (UIView *subview in view.subviews) {
        searchTextField = [self searchViewForTextFieldBg:subview];
        if (searchTextField) {
            break;
        }
    }
    return searchTextField;
}
like image 39
jithin Avatar answered Oct 12 '22 21:10

jithin