Searchbar cancel button not visible only on iPad

2019-02-11 08:21发布

问题:

First I want to say I didn't find any good answer about it in Swift. I created search bar. On button click it shows and on cancel it hides the searchbar. It is working properly, cancel button is visible on all iPhones but for some reason not on iPad. What should cause this?

That is how I create the searchbar:

//Create searchbar
    func createSearchBar(){

        searchBar.showsCancelButton = true
        searchBar.tintColor = UIColor(red:0.184, green:0.996, blue:0.855, alpha:1.00)
        searchBar.placeholder = "Search brands"
        searchBar.delegate = self



        searchBar.hidden =  false
        searchBar.alpha = 0

        navigationItem.titleView = searchBar
        navigationItem.setLeftBarButtonItem(menuButton, animated: true)
        navigationItem.setRightBarButtonItem(searchButtton, animated: true)


        UIView.animateWithDuration(0.5, animations: {
            self.searchBar.alpha = 1
            }, completion: { finished in
                self.searchBar.becomeFirstResponder()
        })


    }

回答1:

Faced the same one of my project. I've posted on apple forum and lot of developers commented as a xcode bug. So I added the cancel button manually for ipad views

 func configureCancelBarButton() {
    let cancelButton = UIBarButtonItem()
    cancelButton.image = UIImage(named: "cancelButton")
    cancelButton.action = #selector(viewController.ipadCancelButton(_:))
    cancelButton.target = self
    self.navigationItem.setRightBarButtonItem(cancelButton, animated: true)
}

And I previously posted an answer about this question. Check that too. :)



回答2:

https://developer.apple.com/documentation/uikit/uisearchbar/1624283-showscancelbutton

The value of this property is ignored, and no cancel button is displayed, for apps running on iPad.

Apple add that in documents!