iOS - 自定义UISearchBar的取消按钮

Sat*_*yam 12 cancel-button uisearchbar ios

在我的iOS5 iPhone应用程序中,我使用以下代码设置搜索栏的色调:

searchBar.tintColor = UIColorMake(@"#EFEFEF");
Run Code Online (Sandbox Code Playgroud)

#efefef的RGB值是(239,239,239)
它的工作正常.但是当出现取消按钮时,文本"取消"不可见.我可以自定义带有透明黑白文本的取消按钮吗?
可以自定义吗?

Mar*_*rný 42

您可以使用外观代理自定义iOS 5上的"取消"按钮.您需要更改UIBarButtonItem包含时的外观UISearchBar.例如,要更改"取消"按钮的标题字体,您可以使用:

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];
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案.这不是hacky,很清楚,而且很有效.目前接受的答案可能随时中断. (5认同)

Oma*_*ith 5

您可以搜索子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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如我之前所说,这可能会改变,这是一个黑客,你最好坚持原来,或创建自己的搜索栏.

  • 在ios 7中,它没有找到任何子视图 (2认同)