删除 UISearchBar 中的清除按钮 [英] Remove clear button in UISearchBar

查看:38
本文介绍了删除 UISearchBar 中的清除按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 UISearchBar 中删除清除按钮(灰色 x).我尝试按照 这个答案 中的描述进行操作,但它不起作用.

I want to remove the clear button (gray x) from the UISearchBar. I tried to do it like described in this answer, but it doesn't work.

我将下面的答案和评论中的 Objective-C 代码翻译成以下 Swift 代码:

I translated the Objective-C code from the answer and the comment below to following Swift code:

for subview in searchBar.subviews {
        configureSearchBarView(subview as UIView)
}

func configureSearchBarView(view: UIView) {
    for subview in view.subviews {
        self.configureSearchBarView(subview as UIView)
    }
    if subview.conformsToProtocol(UITextInputTraits) {
        var clearView = view as UITextField
        clearView.clearButtonMode = UITextFieldViewMode.Never
    }
}

不幸的是,这并没有删除清除按钮.

Unfortunatly this doesn't remove the clear button.

另一个答案建议使用 appearanceWhenContainedIn,但此方法似乎并未实现在 Swift 中.

Another answer suggests to work with appearanceWhenContainedIn, but this method doesn't seem to be implemented in Swift.

有什么想法吗?

推荐答案

我找到了解决方案.可以用自定义图像交换清除按钮:

I found a solution. It is possible to exchange the clear button with a custom image:

UISearchBar.appearance().setImage(UIImage(named: "emptyImg"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Normal)
UISearchBar.appearance().setImage(UIImage(named: "emptyImg"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Highlighted)

emptyImg 是一个包含一个白色像素的 png.在这个答案

emptyImg is an png that contains one white pixel. Found in this answer

这篇关于删除 UISearchBar 中的清除按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆