2014-04-03 59 views
3

我使用这个代码改变的UISearchBar取消按钮标题:更改文字后,无法更改UISearchBar取消按钮标题颜色。

-(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{ 
self.searchDisplayController.searchBar.showsCancelButton = YES; 
UIView* view=_otsinguRiba.subviews[0]; 
for (UIView *subView in view.subviews) { 
    if ([subView isKindOfClass:[UIButton class]]) { 
     UIButton *cancelButton = (UIButton*)subView; 

     if (cancelButton) { 
     [cancelButton setTitle:@"Test") forState:UIControlStateNormal]; 
     [cancelButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; 
     } 
    } 
} 
} 

虽然更改文本正常工作,改变颜色没有。它保持黑色。

回答

10

我发现这个答案在SO一阵子,但我不记得在哪里。以下是我用来设置文本颜色的代码。

[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: 
       [UIColor redColor],NSForegroundColorAttributeName, 
       //[UIColor whiteColor],UITextAttributeTextShadowColor, 
       //[NSValue valueWithUIOffset:UIOffsetMake(0, 1)],UITextAttributeTextShadowOffset, 
       nil] 
     forState:UIControlStateNormal]; 
+0

确实有效。但是你用什么方法通常使用这个代码?已经在' - (void)viewDidLoad'中? – Shiim

+1

这是一个全局设置,将应用于您的应用程序中的所有UISearchBar元素。我通常在'application didFinishLaunchingWithOptions'方法中将这些设置放在应用程序委托类中,因此这些设置将在任何视图控制器加载之前应用。 –

0

您可以利用iOS运行时属性_cancelButton来实现此目的。

UIButton *cancelButton = [self.searchDisplayController.searchBar valueForKey:@"_cancelButton"]; 
[cancelButton setTitleColor:[UIColor yourColor] forState:UIControlStateNormal];