How do you keep the cancel button in the search bar enabled when the keyboard is dismissed?

前端 未结 11 1770
萌比男神i
萌比男神i 2020-12-30 01:23

\"enter \"enter

相关标签:
11条回答
  • 2020-12-30 02:14

    You could do this:

    - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
        [self enableCancelButton];
    }
    
    - (void)enableCancelButton {
        for (UIView *view in _seachBar.subviews) {
            if ([view isKindOfClass:[UIButton class]]) {
                [(UIButton *)view setEnabled:YES];
            }
        }
    }
    

    BUT this is a pretty hackish method and I'm fairly certain it's generally frowned upon by Apple and could potentially lead to the app being rejected. As far as I know, there doesn't seem to be any other way to do what you're trying to do.

    0 讨论(0)
  • 2020-12-30 02:17

    You can use the runtime API to access the cancel button.

    UIButton *btnCancel = [self.searchBar valueForKey:@"_cancelButton"];
    [btnCancel setEnabled:YES];
    

    As far as your question is concerned, there is no way you can enable the cancel button when the keyboard is dismissed, like there is no callback as such.

    0 讨论(0)
  • 2020-12-30 02:22

    Here's a simple way:

    searchBar.resignFirstResponder()
    (searchBar.value(forKey: "_cancelButton") as? UIButton)?.isEnabled = true
    
    0 讨论(0)
  • 2020-12-30 02:26

    Since iOS 7 all the subview of UISearchBar are one level deeper. This should work:

    for (UIView *subView in searchBar.subviews) {
        for (UIView *secondLevelSubview in subView.subviews) {
            if ([view isKindOfClass:[UIButton class]]) {
               [(UIButton *)view setEnabled:YES];
            }
    }
    

    Still hacky and can easily break in the next iOS version.

    0 讨论(0)
  • 2020-12-30 02:26

    Here's a recursive solution that is working for me.

    func enableButtons(_ view:UIView) { for subView in view.subviews { enableButtons(subView) } if let buttonView = view as? UIButton { buttonView.isEnabled = true } }

    0 讨论(0)
提交回复
热议问题