[英]Change Cancel Button BackgroundColor and Text of UISearchBar in iOS7
我有以下代碼可以更改UISearchBar中“取消”按鈕的背景。
for( UIView *subview in self.searchBar.subviews ){
if ([subview isKindOfClass:[UIButton class]]) {
[(UIButton *)subview setEnabled:YES];
[(UIButton *)subview setTitle:@"New Button Text" forState:UIControlStateNormal];
((UIButton *)subview).tintColor = [UIColor colorWithRed:4/255.0 green:119/255.0 blue:152/255.0 alpha:1.0];
}
}
問題是此代碼在iOS7中不起作用! UISearchBar中的視圖結構發生了什么變化?
編輯:在這里測試,這是UISearchBar的新層次結構:
UISearchBar:
---UIView:
------UISearchBarBackground
------UISearchBarTextField
------UINavigationButton
問題是我無法測試if ([sub isKindOfClass:[UINavigationButton class]])
。 此行引發編譯錯誤: Use of undeclared identifier: UINavigationButton
[Edited]
試試這個代碼。
如果要更改所有取消按鈕,請添加AppDelegate
。
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor redColor],
UITextAttributeTextColor,
[UIColor whiteColor],
UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
UITextAttributeTextShadowOffset,
nil]
forState:UIControlStateNormal];
在iOS7中,我們需要添加objectAtIndex:0 and subviews.
iOS7中的searchBar子視圖層次結構已更改,請嘗試以下操作:
in iOS7:
NSArray *searchBarSubViews = [[self.searchBar.subviews objectAtIndex:0] subviews];
iOS6 and before:
NSArray *searchBarSubViews = self.searchBar.subviews;
解決方案:我創建了自己的按鈕。 這樣,我可以管理所有屬性,而不必了解Apple對元素所做的工作
我只需要創建一個UIView aux
即可包含searchBar和新Button。
self.searchBar.showsCancelButton = NO; //don`t show the original cancelButton
self.cancelSearchButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.cancelSearchButton.frame = CGRectMake(250, 6, 60, 31);
[self.cancelSearchButton setTitle:@"Cancelar" forState:UIControlStateNormal];
[self.cancelSearchButton addTarget:self action:@selector(searchBarCancelButtonClicked) forControlEvents:UIControlEventTouchUpInside];
NSString *fontName = [[self.cancelSearchButton titleLabel] font].fontName;
[[self.cancelSearchButton titleLabel] setFont:[UIFont fontWithName:fontName size:11.0]];
UIView *aux = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
aux.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
aux.layer.borderWidth = 1.0f;
aux.layer.borderColor = [UIColor lightGrayColor].CGColor;
aux.layer.cornerRadius = 0.0f;
[aux addSubview:self.searchBar];
[aux addSubview:self.cancelSearchButton];
- (void)searchBarCancelButtonClicked{
//do whatever I want to do here
}
您可以利用iOS運行時屬性_cancelButton
來實現此目的。
UIButton *cancelButton = [self.searchBar valueForKey:@"_cancelButton"];
[cancelButton setTitleColor:[UIColor yourColor] forState:UIControlStateNormal];
用於更改文字
[self.searchBar setValue:@"customString" forKey:@"_cancelButtonText"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.