learner
learner

Reputation: 11780

Change keyboard color for UISearchBar

I would really like to change the color of the "Search" button on the keyboard to match the theme of my app. But if that is not possible, at least I would like to do

self.searchBar.keyboardAppearance = UIKeyboardAppearanceDark;

But that does not work because, as I guess, the searchBar is not a UITextField. So how might I do this successful? I mean, change the color of the "Search" on the keyboard: whether fully or just the dark theme.

Upvotes: 5

Views: 3317

Answers (5)

Shivam Aditya
Shivam Aditya

Reputation: 402

Swift 5, iOS 14:

If Search bar is present inside a specific view (eg- SearchBarView),

UITextField.appearance(whenContainedInInstancesOf: [SearchBarView.self]).keyboardAppearance = .dark

Will cause change only for the specific search bar inside the SearchBarView.

Else if you want to do for all Search Bars then,

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).keyboardAppearance = .dark

Upvotes: 0

Skaal
Skaal

Reputation: 1274

Swift 4 update, iOS 11+ :

    searchBar.keyboardAppearance = .dark
    searchBar.keyboardAppearance = .light
    searchBar.keyboardAppearance = .default

Upvotes: 1

Frank Gumeta
Frank Gumeta

Reputation: 171

For iOS 8 use

self.searchBar.keyboardAppearance = UIKeyboardAppearance.Dark

Upvotes: 15

Jouhar
Jouhar

Reputation: 288

Try this, it works with IOS 6 , IOS 7 and IOS 8:

[self setKeyboardOnSearchBar:self.searchBar];

And the function:

-(void)setKeyboardOnSearchBar:(UISearchBar *)searchBar
{
    for(UIView *subView in searchBar.subviews) {
        if([subView conformsToProtocol:@protocol(UITextInputTraits)]) {
            [(UITextField *)subView setKeyboardAppearance:UIKeyboardAppearanceAlert];
            [(UITextField *)subView setReturnKeyType:UIReturnKeySearch];
        } else {
            for(UIView *subSubView in [subView subviews]) {
                if([subSubView conformsToProtocol:@protocol(UITextInputTraits)]) {
                    [(UITextField *)subSubView setReturnKeyType:UIReturnKeySearch];
                    [(UITextField *)subSubView setKeyboardAppearance:UIKeyboardAppearanceAlert];
                }
            }
        }
    }
}

Upvotes: 5

Konsol Labapen
Konsol Labapen

Reputation: 2434

Try the following

for(UIView *subView in self.searchBar.subviews) {
        if([subView conformsToProtocol:@protocol(UITextInputTraits)]) {
            [(UITextField *)subView setKeyboardAppearance: UIKeyboardAppearanceDark];
        }
    }

Upvotes: 3

Related Questions