UISearchBar Cancel Button

Using a UISearchBar with showCancelButton=YES on iOS 5. Would like the cancel button to stay enabled when the keyboard drops down. Using the following code seems not to work:

    for (id subView in self.searchControl.subviews)
    {
        if ([subView isKindOfClass:[UIButton class]])
        {
            UIButton *cancelButton = (UIButton *)subView;
            [cancelButton setEnabled:YES];
            break;
        }         
    }

The subView is actually a UINavigationButton which appears not to be subclassed off of UIButton. What am I missing here??????? Also cannot find any info on the UINavigationButton class in the Apple docs.


Set your searchbar delegate and than put this code.

- (void) searchBarSearchButtonClicked:(UISearchBar*) theSearchBar
  {
     [theSearchBar resignFirstResponder];
     [theSearchBar setShowsCancelButton:NO animated:YES];
  }
 - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
  {
     [searchBar setShowsCancelButton:YES animated:YES];
  }
  - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  {
     [searchBar resignFirstResponder];
     [searchBar setShowsCancelButton:NO animated:YES];
  }

Swift 3.0

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
     searchBar .resignFirstResponder()
     searchBar.setShowsCancelButton(false, animated: true)
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
     searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
     searchBar.resignFirstResponder()
     searchBar.setShowsCancelButton(false, animated: true)
}

Just to improve upon what Kurt Spindler said on his post. Though this might not be superior but it is more contained. I use dispatch to do the same thing.

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    for (UIView *subview in searchBar.subviews)
    {
        if ([subview isKindOfClass:[UIButton class]])
        {
            int64_t delayInSeconds = .001;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                UIButton * cancelButton = (UIButton *)subview;
                [cancelButton setEnabled:YES];
            });
            break;
        }
    }
}

This should work for everyone who needs help keep cancel enabled. Make sure that you hide it later either with the cancel or Search clicked.

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}

我在搜索栏取消按钮上放置了一个自定义取消按钮。

链接地址: http://www.djcxy.com/p/44276.html

上一篇: UISearchbar clearButton强制显示键盘

下一篇: UISearchBar取消按钮