可以更改搜索栏的文本颜色吗?我似乎无法访问UISearchBarTextField类...
(是否可以更改搜索栏的文字颜色?由于无法访问 UISearchBarTextField 类,因此无法实现。)可以更改搜索栏的文本颜色吗?我似乎无法访问UISearchBarTextField类...
(是否可以更改搜索栏的文字颜色?由于无法访问 UISearchBarTextField 类,因此无法实现。)首先,在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]];
iOS 5以后,正确的方法是使用外观协议。
例如:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];
原始的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]];
[[UITextField appearanceWhenContainedIn:[self class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:14]}];