iPhone UISearchBar & keyboardAppearance

倖福魔咒の 提交于 2019-11-30 07:12:57
Erich Wood

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];

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...

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];

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!