[英]iOS - Customizing Cancel button of UISearchBar
在我的iOS5 iPhone應用程序中,我使用以下代碼設置搜索欄的色調:
searchBar.tintColor = UIColorMake(@"#EFEFEF");
#efefef的RGB值是(239,239,239)
它的工作正常。 但是當出現取消按鈕時,文本“取消”不可見。 我可以自定義帶有透明黑白文本的取消按鈕嗎?
可以自定義嗎?
您可以使用外觀代理自定義iOS 5上的“取消”按鈕。 您需要在UISearchBar
包含時更改UIBarButtonItem
外觀。 例如,要更改“取消”按鈕的標題字體,您可以使用:
NSDictionary *attributes =
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor], UITextAttributeTextColor,
[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5], UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,
[UIFont systemFontOfSize:12], UITextAttributeFont,
nil];
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil]
setTitleTextAttributes:attributes forState:UIControlStateNormal];
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil]
setTitleTextAttributes:attributes forState:UIControlStateHighlighted];
您可以搜索UISearchBar
視圖並找到取消按鈕,這樣做很危險,因為按鈕可能會更改。例如,您可以在viewWillAppear
添加它
- (void) viewWillAppear:(BOOL)animated
{
//show the cancel button in your search bar
searchBar.showsCancelButton = YES;
//Iterate the searchbar sub views
for (UIView *subView in searchBar.subviews) {
//Find the button
if([subView isKindOfClass:[UIButton class]])
{
//Change its properties
UIButton *cancelButton = (UIButton *)[sb.subviews lastObject];
cancelButton.titleLabel.text = @"Changed";
}
}
}
正如我之前所說,這可能會改變,這是一個黑客,你最好堅持原來,或創建自己的搜索欄。
從iOS5開始,您可以使用此代碼編輯導航欄,工具欄,Tabbar等等...
NSDictionary *textTitleOptions = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor darkGrayColor],
UITextAttributeTextColor,
[UIColor whiteColor],
UITextAttributeTextShadowColor, nil];
[[UINavigationBar appearance] setTitleTextAttributes:textTitleOptions];
我沒有用搜索欄對它進行測試,但它的工作方式應該類似。
此方法適用於IOS7
for (UIView *view in searchBar.subviews)
{
for (id subview in view.subviews)
{
if ( [subview isKindOfClass:[UIButton class]] )
{
// customize cancel button
UIButton* cancelBtn = (UIButton*)subview;
[cancelBtn setEnabled:YES];
break;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.