简体   繁体   English

将UISearchBar取消按钮更改为图标

[英]Change UISearchBar Cancel button to icon

I want to change the UISearchBar 's Cancel button to one that only has an image, and no text. 我想将UISearchBarCancel按钮更改为只有图像而没有文本的按钮。 Here's where I got to so far from original behaviour 这是我从原始行为到目前为止所处的位置

在此输入图像描述

to this 对此

在此输入图像描述

A step in the right direction, but the problem is the button is too wide. 朝着正确的方向迈出了一步,但问题是按钮太宽了。 When I debug the view, I can see that it has button label insets of 11 points on left and right. 当我调试视图时,我可以看到左侧和右侧有11个点的按钮标签插入。 Does anyone know how to make the button fit the content size? 有谁知道如何使按钮适合内容大小? The image is square. 图像是方形的。

Here's my code for customising the button: 这是我自定义按钮的代码:

UIBarButtonItem *barButtonAppearanceInSearchBar;

if (IOS9) {
    barButtonAppearanceInSearchBar = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]];
} else {
    barButtonAppearanceInSearchBar = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
}

barButtonAppearanceInSearchBar.image = [UIImage imageNamed:@"Close"];
barButtonAppearanceInSearchBar.title = nil;

Another weird issue is that when I dismiss the search bar and activate it again, the button image turns dark (it's still there, I can see it when debugging the views), so it looks like this 另一个奇怪的问题是,当我关闭搜索栏并再次激活它时,按钮图像变暗(它仍然存在,我可以在调试视图时看到它),所以它看起来像这样

在此输入图像描述

Any idea how to keep the icon white? 知道如何保持图标白色吗? I tried this method below, but without results: 我在下面尝试了这种方法,但没有结果:

- (void)willPresentSearchController:(UISearchController *)searchController {

    searchController.searchBar.tintColor = [UIColor whiteColor];
}

Use image rendering and tint color. 使用图像渲染和色调颜色。

barButtonAppearanceInSearchBar.image = [[UIImage imageNamed:@"Close"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
barButtonAppearanceInSearchBar.tintColor = [UIColor whiteColor];
barButtonAppearanceInSearchBar.title = nil;

Here's the Swift 4.1 Version of @jamesBlake 's answer: 这是@jamesBlake的答案的Swift 4.1版本:

 func setUpSearchBar() {

    let barButtonAppearanceInSearchBar: UIBarButtonItem?
    barButtonAppearanceInSearchBar = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
    barButtonAppearanceInSearchBar?.image = UIImage(named: "Home.png")?.withRenderingMode(.alwaysTemplate)
    barButtonAppearanceInSearchBar?.tintColor = UIColor.white
    barButtonAppearanceInSearchBar?.title = nil
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM