在 iOS 7 中,UISearchBar 的 cancel button 預設顯示英文 Cancel。若要改成中文,不能直接取得公開屬性,需要從 searchBar 的子檢視中找到 UINavigationButton。
可先列印 searchBar 的子檢視,會發現 cancel button 位於更深一層。
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]];
}
}完整設定時,可先建立 searchBar,開啟 showsCancelButton,再遍歷子檢視。
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 240, 24)];
searchBar.delegate = self;
[searchBar setShowsCancelButton:YES];
[searchBar setPlaceholder:@"搜尋劇集"];這種做法依賴系統內部檢視結構,後續 iOS 版本若調整 UI 層級,可能需要重新調整。