標籤:ios7 searchbar
通過 [searchBarsetShowsCancelButton:YES];設定之後預設是“cancel”,想改為中文的
在stackoverflow上參考了很多方法都沒用
這裡的關鍵是要擷取到 searchbar中得 cancelButton
通過列印 [searchbar subviews]
得到結果如下
(lldb) po [searchBar subviews]
<__NSArrayM 0xd6b0db0>(
<UIView: 0xd6aab30; frame = (0 0; 240 24); clipsToBounds = YES; autoresize =
+H; layer = <CALayer: 0xd6aab90>>
)
也就是其只有一個subview,在stackoverflow上得到些其實
這個cancelbutton在更深一層
列印
[[[searchBar subviews] objectAtIndex:0] subviews]
得到結果:
(lldb) po [[[searchBar subviews] objectAtIndex:0] subviews]
<__NSArrayM 0xd6b0dd0>(
<UISearchBarBackground: 0xd6ab370; frame = (0 0; 240 24); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0xd6ab4c0>>,
<UINavigationButton: 0xd6abef0; frame = (0 0; 54 30); opaque = NO; layer = <CALayer: 0xd6ac020>>,
<UISearchBarTextField: 0xd6acbe0; frame = (0 0; 0 0); text = ‘‘; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0xd6acdf0>>
)
也就是這個UINavigationButton,對它進行設定
代碼如下
searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 240, 24)]; //導航條的搜尋條 searchBar.delegate = self; [searchBar setShowsCancelButton:YES]; [searchBar setTintColor:[UIColor blackColor]]; [searchBar setBarTintColor:[UIColor clearColor]]; [searchBar setPlaceholder:@"搜尋集"]; for(UIView *view in [[[searchBar subviews] objectAtIndex:0] subviews]) { if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) { UIButton * cancel =(UIButton *)view; [cancel setTitle:@"取消" forState:UIControlStateNormal]; [cancel setTintColor:[UIColor blackColor]]; [cancel.titleLabel setTextColor:[UIColor blackColor]]; } }