Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel button is not shown in UISearchBar

I have UICollectionView. On clicking search button in UINavigationBar, I am adding the UISearchController's searchbar as titleview for UINavigationItem. For iPhone it is working properly. For iPad the cancel button is not shown. The Searchbar alone takes the entire width.

enter image description here

Can anyone help me out on this?. Thanks in advance.

like image 667
Sheik_101 Avatar asked May 27 '15 06:05

Sheik_101


4 Answers

I had the same problem, on iPhone the search cancel was shown well, but on iPad it didn't.

The workaround of wrapping the UISearchBar in another UIView didn't work well for me since it had different appearance and wrong width on rotation.

My solution is a simple one - use search WITHOUT cancel, and add cancel as a UIBarButtonItem.

like image 21
Tal Haham Avatar answered Oct 09 '22 02:10

Tal Haham


iOS7 does not show the cancel button when added to a navigation bar.You can put searchbar in another view like this.

UISearchBar *searchBar = [UISearchBar new];
searchBar.showsCancelButton = YES;
[searchBar sizeToFit];
UIView *viewForSearchBar = [[UIView alloc]initWithFrame:searchBar.bounds];
[viewForSearchBar addSubview:searchBar];
self.navigationItem.titleView = viewForSearchBar;
like image 123
Nikita Khandelwal Avatar answered Oct 09 '22 03:10

Nikita Khandelwal


Added rightBarButtonItem with selector will work fine for me. And adding searchBar inside view before setting to navigation title view was not showing properly.
Code:- 
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.dismissView))
func dismissView() {
        if self.controller?.navigationController?.popViewController(animated: true) == nil {
            self.controller?.dismiss(animated: true, completion: nil)
        }
    }
like image 4
Sagar Daundkar Avatar answered Oct 09 '22 03:10

Sagar Daundkar


As per apple documentation setShowsCancelButton

Cancel buttons are not displayed for apps running on iPad, even when you specify YES for the showsCancelButton parameter.

I am not sure about the alternate but this is what apple provides us.

enter image description here

like image 3
Muhammad Usman Aleem Avatar answered Oct 09 '22 03:10

Muhammad Usman Aleem