Jonathan Tuzman
Jonathan Tuzman

Reputation: 13283

Search cursor disappearing when cancel button hidden

I followed the great directions in this post to subclass a search bar and search controller that does not show the cancel button. However, there is now no cursor in my search bar when I start editing. I've tried setting the tint for the search bar, which I've seen as an answer in many posts, in various delegate methods. The tint is technically being set correctly, as I can see when I test it by setting my search controller to be the standard UISearchController. But as soon as I set it to my subclass SearchControllerWithoutCancel the cursor goes away.

Here are my subclasses:

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

}

class SearchControllerWithoutCancel: UISearchController, UISearchBarDelegate {

lazy var _searchBar: SearchBarWithoutCancel = {
    [unowned self] in
    let result = SearchBarWithoutCancel(frame: .zero)
    result.delegate = self

    return result
    }()

override var searchBar: UISearchBar {
    get {
        return _searchBar
    }
}

}

And here's my addSearchController method which I call from viewDidLoad()

func addSearchController() {
    searchController.searchResultsUpdater = self

    searchController.dimsBackgroundDuringPresentation = false
    searchController.hidesNavigationBarDuringPresentation = false

    searchController.searchBar.autocapitalizationType = .none
    searchController.searchBar.searchBarStyle = .minimal
    searchController.searchBar.tintColor = UIColor.black

    self.definesPresentationContext = true

    tableView.tableHeaderView = searchController.searchBar
}

Has anyone encountered this before? Thanks :)

Upvotes: 1

Views: 239

Answers (1)

Alexis Contour
Alexis Contour

Reputation: 258

indeed when the cancel button is hidden, the cursor tint color resets itself

in your SearchBarWithoutCancel remove the layoutSubviews and override setShowsCancelButton :

override func setShowsCancelButton(_ showsCancelButton: Bool, animated: Bool) {
    //nothing
}}

objective-c version

-(void) setShowsCancelButton:(BOOL)show animated:(BOOL)animated
{
    //nothing
}

Upvotes: 0

Related Questions