Hiding Cancel button on search bar in UISearchController

前端 未结 6 870
离开以前
离开以前 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: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
            }
        }
    }
    

提交回复
热议问题