iPhone UISearchBar & keyboardAppearance

后端 未结 4 1840
说谎
说谎 2020-12-30 11:07

When the keyboard appears, I want to set the

keyboardAppearance = UIKeyboardAppearanceAlert

I\'ve checked the documentation and it looks l

4条回答
  •  一整个雨季
    2020-12-30 11:40

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

提交回复
热议问题