joseph_carney
joseph_carney

Reputation: 1535

iPhone UISearchBar & keyboardAppearance

When the keyboard appears, I want to set the

keyboardAppearance = UIKeyboardAppearanceAlert

I've checked the documentation and it looks like you can only change the keyboardType.

Can this be done without violating any of Apple's private API's ?

Upvotes: 9

Views: 7311

Answers (4)

Erich Wood
Erich Wood

Reputation: 361

The best way that I found to do this, if you want to do it throughout your app, is to use Appearance on UITextField. Put this in your AppDelegate on launch.

[[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceDark];

Upvotes: 35

stonemonk
stonemonk

Reputation: 2382

This no longer works on iOS 7 because the UISearchBar view hierarchy has changed. The UITextView is now a subview of the first subview (e.g. its in the searchBar.subviews[0].subviews array).

A more future proof way to do this would be to check recursively the entire view hierarchy, and to check for UITextInputTraits protocol rather than UITextField, since that is what actually declares the method. A clean way of doing this is to use categories. First make a category on UISearchBar that adds this method:

- (void) setKeyboardAppearence: (UIKeyboardAppearance) appearence {
    [(id<UITextInputTraits>) [self firstSubviewConformingToProtocol: @protocol(UITextInputTraits)] setKeyboardAppearance: appearence];
}

Then add a category on UIView that adds this method:

- (UIView *) firstSubviewConformingToProtocol: (Protocol *) pro {
    for (UIView *sub in self.subviews)
        if ([sub conformsToProtocol: pro])
            return sub;

    for (UIView *sub in self.subviews) {
        UIView *ret = [sub firstSubviewConformingToProtocol: pro];
        if (ret)
            return ret;
    }

    return nil;
}

You can now set the keyboard appearance on the search bar in the same way you would a textfield:

[searchBar setKeyboardAppearence: UIKeyboardAppearanceDark];

Upvotes: 9

user265926
user265926

Reputation:

This should do it:

for(UIView *subView in searchBar.subviews)
    if([subView isKindOfClass: [UITextField class]])
        [(UITextField *)subView setKeyboardAppearance: UIKeyboardAppearanceAlert];

didn't find any other way of doing...

Upvotes: 27

Daddy
Daddy

Reputation: 9035

keyboardAppearance is a property of the UITextInputTraitsProtocol, which means that the property is set via the TextField object. I'm not aware of what an Alert Keyboard is, from the SDK it's a keyboard suitable for an alert.

here's how you access the property:

UITextField *myTextField = [[UITextField alloc] init];
myTextField.keyboardAppearance = UIKeyboardAppearanceAlert;

Now when the user taps the text field and the keyboard shows up, it should be what you want.

Upvotes: -2

Related Questions