0

我正在使用下面的代码。它在 IOS 6.x 中运行良好。从 Xcode 4.6.x 构建。但是该代码在从 xcode 5.x 构建的 IOS 7.x 中不再起作用。

我的目标是在用户开始在 UISearchBar 中编辑时显示自定义图像来代替 UISearchBar 的取消按钮。

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
    UIButton *cancelButton = nil;
    for(UIView *subView in searchBar.subviews){
        if([subView isKindOfClass:UIButton.class]){
            cancelButton = (UIButton*)subView;
        }
    }
    [cancelButton setTintColor:[UIColor colorWithRed:167.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:1.0f]];
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"customKeyboardIcon.png"] forState:UIControlStateNormal];
    [cancelButton setTitle:nil forState:UIControlStateNormal];
}
4

2 回答 2

6

中的取消按钮UISearchBar是类型UIBarButton。我这样做的方式如下(适用于 iOS 5、6、7):

 [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundImage:cancelButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

如果您不希望所有人都使用自定义取消按钮UISearchBar,只需创建一个自定义UISearchBar类并将其替换为appearanceWhenContainedIn:[UISearchBar class]您的新自定义类。

删除文本:

[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@""];

至于图像,要么调整图像资源,要么创建一个UIImage带有一些插图的插图,(修补插入,直到获得预期的结果):

     UIImage *cancelButtonImage = [UIImage imageNamed:SEARCH_BAR_CANCEL_BUTTON];
cancelButtonImage = [cancelButtonImage resizableImageWithCapInsets:CANCEL_BUTTON_IMAGE_INSETS];
于 2013-10-21T12:01:45.857 回答
0

检查我使用的这段代码:

-(void) colorCancelButton
{
    UIButton *cancelButton = [self getCancelButton];
        [cancelButton setTintColor:[Util colorFromHex:@"#D6D1CF"]];
        [cancelButton setTitleColor:[Util colorFromHex:@"333333"] forState:UIControlStateNormal];
}

-(UIButton*) getCancelButton
{
    UIButton *cancelButton = nil;
    for(UIView *subView in self.subviews){
        if([subView isKindOfClass:UIButton.class])
        {
            cancelButton = (UIButton*)subView;
        }
    }
    return cancelButton;
}
于 2014-01-28T18:07:38.113 回答