UISearchBar Cancel Button

前端 未结 6 2788
别那么骄傲
别那么骄傲 2021-02-20 03:35

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:<

6条回答
  •  一整个雨季
    2021-02-20 04:22

    I know this one is old, but I was able to solve it and I couldn't find anything else on SO that solved it for me, so here's what worked (in Swift 3):

    Enable the cancel button when the keyboard hides. Add this to viewDidLoad():

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
    

    in the keyboardNotification(notification:) method, react to the keyboardDidHide notification:

    func keyboardNotification(notification: NSNotification) {
        if notification.name == Notification.Name.UIKeyboardDidHide {
            self.enableSearchCancelButton()
        }
    }
    

    The enableSearchCancelButton is taken from what others have answered here.

    func enableSearchCancelButton() {
        //enable the cancel button
        for view1 in searchBar.subviews {
            for view2 in view1.subviews {
                if let button = view2 as? UIButton {
                    button.isEnabled = true
                    button.isUserInteractionEnabled = true
                }
            }
        }
    }
    

    Finally, don't forget to remove the view controller as an observer:

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    

提交回复
热议问题