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

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

\"enter \"enter

11条回答
  •  一个人的身影
    2020-12-30 02:11

    Try this simple solution, works perfect for me

    extension UISearchBar {
    
        func enableCancelButton(in view: UIView) {
    
            view.subviews.forEach {
                enableCancelButton(in: $0)
            }
    
            if let cancelButton = view as? UIButton {
                cancelButton.isEnabled = true
                cancelButton.isUserInteractionEnabled = true
            }
        }
    }
    
    extension ViewController: UISearchBarDelegate {
    
        func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
            DispatchQueue.main.async {
                searchBar.enableCancelButton(in: searchBar)
            }
        }
    }
    

提交回复
热议问题