从Xcode 5.x自定义IOS 7构建中的UISearchBar取消按钮

NSC*_*Cry 0 ios ios7 xcode5

我正在使用下面的代码.它在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];
}
Run Code Online (Sandbox Code Playgroud)

Dur*_*adu 6

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

 [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundImage:cancelButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
Run Code Online (Sandbox Code Playgroud)

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

删除文字:

[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@""];
Run Code Online (Sandbox Code Playgroud)

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

     UIImage *cancelButtonImage = [UIImage imageNamed:SEARCH_BAR_CANCEL_BUTTON];
cancelButtonImage = [cancelButtonImage resizableImageWithCapInsets:CANCEL_BUTTON_IMAGE_INSETS];
Run Code Online (Sandbox Code Playgroud)