如何更改文本颜色UISearchBar的iOS 7?
在iOS 6,我是子类化UISearchBar和layoutSubviews定制UITextField子视图的属性UISearchBar.
但在iOS 7,UISearchBar没有UITextField作为其子视图.如何解决这个问题?
Tos*_*lji 100
在iOS 7中访问文本字段,您必须在级别上重申更多.像这样更改你的代码
for (UIView *subView in self.searchBar.subviews)
{
for (UIView *secondLevelSubview in subView.subviews){
if ([secondLevelSubview isKindOfClass:[UITextField class]])
{
UITextField *searchBarTextField = (UITextField *)secondLevelSubview;
//set font color here
searchBarTextField.textColor = [UIColor blackColor];
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:这是非公共API
要么
您可以使用UIControls的外观属性,Like
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
Run Code Online (Sandbox Code Playgroud)
注意:外观代理可用于iOS 9.0+ OutPut

您可以设置" tintcolor应用于"中的关键元素search bar.
使用tintColor进行着色前景元素.
使用barTintColor进行着色的栏背景.
在iOS v7.0中,UIView的所有子类都从基类派生tintColor的行为.有关更多信息,请参阅UIView级别的tintColor讨论. Apple Doc
San*_*tix 95
您可以设置文本颜色
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];
Run Code Online (Sandbox Code Playgroud)
Gra*_*son 35
对于XCode 6(iOS8 SDK),以下操作无效
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];
Run Code Online (Sandbox Code Playgroud)
但以下DOES工作(部署到iOS7和iOS8)
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
Run Code Online (Sandbox Code Playgroud)
虽然UIAppearance协议确实是"公共API",但UITextField支持这一点并不正确.
如果您查看UITextField.h并查找字符串"UI_APPEARANCE_SELECTOR",您将看到它没有此字符串的实例.如果你看看UIButton,你会发现很多 - 这些都是UIAppearance API官方支持的所有属性.众所周知UIAextField不受UIAppearance API的支持,因此Sandeep的答案中的代码并不总是有效,而且实际上并不是最好的方法.
这是一篇有用链接的有用帖子:http://forums.xamarin.com/discussion/175/uitextfield-appearance
不幸的是,正确的方法很麻烦 - 遍历子视图(或iOS7的主要子视图的子视图)并手动设置.否则你将得到不可靠的结果.但是你可以为UISearchBar创建一个类别并添加一个setTextColor:(UIColor*)颜色方法.例:
- (void)setTextColor:(UIColor*)color
{
for (UIView *v in self.subviews)
{
if([Environment isVersion7OrHigher]) //checks UIDevice#systemVersion
{
for(id subview in v.subviews)
{
if ([subview isKindOfClass:[UITextField class]])
{
((UITextField *)subview).textColor = color;
}
}
}
else
{
if ([v isKindOfClass:[UITextField class]])
{
((UITextField *)v).textColor = color;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
警告:这应该导致应用程序拒绝!
KVC FTW.这样做对我来说.
UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
searchField.textColor = [UIColor redColor];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48242 次 |
| 最近记录: |