Hiding Cancel button on search bar in UISearchController

前端 未结 6 869
离开以前
离开以前 2020-12-07 02:08

I\'m trying to hide the Cancel button of the search bar in the UISearchController, but unfortunately setting the following in viewDidLoad() does not work:

ov         


        
相关标签:
6条回答
  • 2020-12-07 02:28

    The same answer as given by @Griffith and @Abhinav but using extension:

    extension UISearchBar {
        override open func layoutSubviews() {
            super.layoutSubviews()
            setShowsCancelButton(false, animated: false)
        }
    }
    

    This code is from Swift 4.

    0 讨论(0)
  • 2020-12-07 02:41

    Hide the Cancel button in search bar delegate methods and set your delegate searchController.searchBar.delegate=self UISearchBarDelegate

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    
    }
    
    func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    
    }
    
    0 讨论(0)
  • 2020-12-07 02:41

    Try subclassing UISearchBar and implement:

    override func layoutSubviews() {
       super.layoutSubviews()
       self.setShowsCancelButton(false, animated: false)
    }
    

    This SO thread may help you more in this direction.

    0 讨论(0)
  • 2020-12-07 02:41
    func didPresentSearchController(_ searchController: UISearchController) {
        searchController.searchBar.becomeFirstResponder()
        searchController.searchBar.showsCancelButton = true
    }
    
    
    func didDismissSearchController(_ searchController: UISearchController) {
        searchController.searchBar.showsCancelButton = false
    }
    

    In my case all the above solutions dint work. You need to show in didPresentSearchController and hide it in didDismissSearchController. Earlier I was just hiding in didDismissSearchController which was still showing Cancel button on cancelling.

    0 讨论(0)
  • 2020-12-07 02:47

    Rejoice! As of iOS 13, there is access to automaticallyShowsCancelButton on UISearchController. Set it to false to hide the cancel button.

    0 讨论(0)
  • 2020-12-07 02:49

    I ended up subclassing both UISearchBar and UISearchController as suggested:

    CustomSearchBar.swift

    import UIKit
    
    class CustomSearchBar: UISearchBar {
    
        override func layoutSubviews() {
            super.layoutSubviews()
            setShowsCancelButton(false, animated: false)
        }
    }
    

    CustomSearchController.swift

    import UIKit
    
    class CustomSearchController: UISearchController, UISearchBarDelegate {
    
        lazy var _searchBar: CustomSearchBar = {
            [unowned self] in
            let result = CustomSearchBar(frame: CGRectZero)
            result.delegate = self
    
            return result
        }()
    
        override var searchBar: UISearchBar {
            get {
                return _searchBar
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题