ios 按下 UISearchBar x 按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29135594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:15:44  来源:igfitidea点击:

UISearchBar x button pressed

iosxcodedelegatesuisearchbar

提问by Fabio

How handle the event when press the 'x' button?

按下“x”按钮时如何处理事件?

I try this method but not works.

我尝试了这个方法,但没有用。

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{

}

enter image description here

在此处输入图片说明

回答by Eric Johnson

I don't think there's an easy way to hook into the X button.

我认为没有一种简单的方法可以连接到 X 按钮。

However, you can hook into its direct consequence: cleared text.

但是,您可以了解其直接后果:清除文本。

Try this:

尝试这个:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText == "" {
        print("UISearchBar.text cleared!")
    }
}

The side effect is this also gets called when you manually clear your text.

副作用是当您手动清除文本时也会调用它。

回答by funct7

A rather hacky way to do it but this works.

一种相当hacky的方式来做到这一点,但这是有效的。

private var didTapDeleteKey = false

func searchBar(_ searchBar: UISearchBar,
               shouldChangeTextIn range: NSRange,
               replacementText text: String) -> Bool
{
    didTapDeleteKey = text.isEmpty

    return true
}

func searchBar(_ searchBar: UISearchBar,
               textDidChange searchText: String)
{
    if !didTapDeleteKey && searchText.isEmpty {
        // Do something here
    }

    didTapDeleteKey = false
}

The success of this code hinges on the fact that when tapping the clear button of the search bar, searchBar(_:shouldChangeTextIn:replacementText:) -> Boolis not called. Instead when the delete button of the keyboard is tapped, the method is called.

这段代码的成功取决于当点击搜索栏的清除按钮时,searchBar(_:shouldChangeTextIn:replacementText:) -> Bool不会被调用。相反,当点击键盘的删除按钮时,会调用该方法。

回答by Kedar Sukerkar

Swift 5.2, Xcode 11.4

斯威夫特 5.2,Xcode 11.4

This one worked for me.

这个对我有用。

if let searchTextField = self.categoriesSearchBar.value(forKey: "searchField") as? UITextField , let clearButton = searchTextField.value(forKey: "_clearButton")as? UIButton {

     clearButton.addTarget(self, action: #selector(self.yourFunction), for: .touchUpInside)
}

回答by Dejan

Simplest solution in Swift 5.0

Swift 5.0 中最简单的解决方案

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText.isEmpty {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            searchBar.resignFirstResponder()
        }
    }
}

回答by Eray Diler

I had the same issue, tried to solve it with accessing searchBar's subview textField but it caused my app crash, and with a last effort i found this post.

我遇到了同样的问题,试图通过访问 searchBar 的子视图 textField 来解决它,但它导致我的应用程序崩溃,最后我找到了这篇文章

Another issue was that,

另一个问题是,

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

is being called twice when cancel button clicked, see also this.

单击取消按钮时将被调用两次,另请参见this

And lastly what i did is;

最后我所做的是;

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (![searchText isEqualToString:self.searchText]) {
        self.searchText = searchText;
        return;
    }
    NSLog(@"Clear clicked");
}

This solved my issue.

这解决了我的问题。

回答by Mona

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length == 0) {
         //clear button (x) on the search bar is cliecked, so clear the table
        [self clearTable];
    }
}

回答by Dj tropycool

This works for me

这对我有用

-(UITextField*)getUITexfieldInUISearchBar:(UIView*)aSearchBar{
UITextField *searchBarTextField;
for (UIView *subView in [aSearchBar subviews]){
    if ([subView isKindOfClass:[UITextField class]])
    {
        searchBarTextField = (UITextField *)subView;
        [searchBarTextField setDelegate:self];
        break;

    }else if ([subView isKindOfClass:[UIView class]]){
        [self getUITexfieldInUISearchBar:subView];
    }
}
  return searchBarTextField;
}

And you can use the TextFields Delegate

你可以使用 TextFields 委托

- (BOOL)textFieldShouldClear:(UITextField *)textField {
   //Do something here...
}

回答by Mohan

self.mySearchBar.searchTextField.delegate = self

self.mySearchBar.searchTextField.delegate = self

extension myViewController: UISearchTextFieldDelegate {

扩展 myViewController: UISearchTextFieldDelegate {

func textFieldShouldClear(_ textField: UITextField) -> Bool {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        self.mySearchBar.searchTextField.resignFirstResponder()
    }
    return true
}

}

}

回答by Karanveer Singh

When you press the cross button on Search Bar, following method gets called:

当您按下搜索栏上的十字按钮时,将调用以下方法:

func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
}

回答by S R Nayak

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){
    print("searchText: \(searchText)")
    if searchText.count > 0
    {
        // Show ur content
    }
    else
    {
        // Hide your content
    }
}