iOS - 自定义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开始,您可以使用此代码编辑导航栏,工具栏,选项卡栏等...

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;
            }
        }
    }

检查此 https://stackoverflow.com/a/18150826/1767686

最新更新