更改iOS搜索栏的文本颜色

8

可以更改搜索栏的文本颜色吗?我似乎无法访问UISearchBarTextField类...

(是否可以更改搜索栏的文字颜色?由于无法访问 UISearchBarTextField 类,因此无法实现。)
4个回答

19

首先,在UISearchBar中找到子视图,然后在子视图中找到UITextField,最后更改颜色。

尝试使用以下代码:

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

适用于 iOS 5 及以上版本

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

用这种方式可能会起作用,但如果苹果决定玩弄视图层次结构,则容易出现问题,请参见下面使用外观协议的解决方案。 - Tom Susel

11

iOS 5以后,正确的方法是使用外观协议。

例如:

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

2

原始的UISearchBar层次结构已经改变,因此UITextField不再是直接的子视图。下面的代码不会做出任何关于UISearchBar层次结构的假设。

这也非常有用,当你不想在整个应用程序中更改搜索栏的文本颜色时(例如使用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];
        }
    }
}

使用方法:

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

2
您可以在控制器中这样设置属性。
[[UITextField appearanceWhenContainedIn:[self class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:14]}];

*请注意,这将更改控制器中的所有UITextFields。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接