简体   繁体   English

更改搜索栏ios的文本颜色

[英]Change text color of search bar ios

Is it possible to change the text color of the search bar? 是否可以更改搜索栏的文字颜色? I don't seem to have access to the UISearchBarTextField class... 我似乎无法访问UISearchBarTextField类...

firstly, you find the subview in UISearchBar , then find the UITextField in sub View then change color 首先,你在UISearchBar找到子视图,然后在子视图中找到UITextField然后改变颜色

Try this code:- 试试这个代码: -

 for(UIView *subView in searchBar.subviews){
            if([subView isKindOfClass:UITextField.class]){
                [(UITextField*)subView setTextColor:[UIColor blueColor]];
            }
        }

for Ios 5 + 对于Ios 5 +

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];

As of iOS 5, the right way to do this is using the appearance protocol. 从iOS 5开始,正确的方法是使用外观协议。

For example: 例如:

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];

You can set the attributes like so, call this in your controller. 您可以像这样设置属性,在控制器中调用它。

[[UITextField appearanceWhenContainedIn:[self class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:14]}];

*note that this will change all UITextFields in your controller *请注意,这将更改控制器中的所有UITextField

The original UISearchBar hierarchy has changed since the original post and the UITextField is no longer a direct subview. 自原始帖子以来,原始UISearchBar层次结构已更改,并且UITextField不再是直接子视图。 The below code makes no assumptions about the UISearchBar hierarchy. 以下代码不对UISearchBar层次结构进行任何假设。

This is also useful when you don't want to change the search bar's text color throughout the entire application (ie using appearanceWhenContainedIn ). 当您不想在整个应用程序中更改搜索栏的文本颜色(即使用appearanceWhenContainedIn )时,这也很有用。

/**
 * A recursive method which sets all UITextField text color within a view.
 * Makes no assumptions about the original view's hierarchy.
 */
+(void) setAllTextFieldsWithin:(UIView*)view toColor:(UIColor*)color
{
    for(UIView *subView in view.subviews)
    {
        if([subView isKindOfClass:UITextField.class])
        {
            [(UITextField*)subView setTextColor:color];
        }
        else
        {
            [self setAllTextFieldsWithin:subView toColor:color];
        }
    }
}

Usage: 用法:

[MyClass setAllTextFieldsWithin:self.mySearchBar toColor:[UIColor blueColor]];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM