UISearchBar 中未显示取消按钮

Cancel button is not shown in UISearchBar

我有UICollectionView。单击 UINavigationBar 中的搜索按钮后,我将 UISearchControllersearchbar 添加为 UINavigationItem 的标题视图。对于 iPhone 它工作正常。对于 iPad,cancel 按钮未显示。搜索栏单独占据了整个宽度。

谁能帮我解决这个问题?。提前致谢。

试试这个。添加显示取消按钮的复选标记。

iOS7 添加到导航时不显示取消按钮 bar.You 可以像这样将搜索栏放在另一个视图中。

UISearchBar *searchBar = [UISearchBar new];
searchBar.showsCancelButton = YES;
[searchBar sizeToFit];
UIView *viewForSearchBar = [[UIView alloc]initWithFrame:searchBar.bounds];
[viewForSearchBar addSubview:searchBar];
self.navigationItem.titleView = viewForSearchBar;

我遇到了同样的问题,在 iPhone 上搜索取消显示良好,但在 iPad 上却没有。

UISearchBar 包裹在另一个 UIView 中的解决方法对我来说效果不佳,因为它具有不同的外观和错误的旋转宽度。

我的解决方案很简单 - 使用不带取消的搜索,并将取消添加为 UIBarButtonItem

Swift 版本:-

我尝试了@Nikita Khandelwal 方法,但它仍然不适合 ipad 视图。这是 swift 代码,已作为更正答案给出:-

let searchBar: UISearchBar = UISearchBar()
searchBar.showCancelButton = true
searchBar.placeholder = "Search Your Job Title"
searchBar.fitToSize()
searchBar.delegate = self //do not need if you delegate searchBar
let viewForSearchBar: UIView = UIView(frame: searchBar.bounds)
viewForSearchBar.addSubview(searchBar)
self.navigationItem.titleView = viewForSearchBar

********* 但还有另一种方法可以正确设置取消按钮并适合视图:-

  1. 将搜索栏设置为导航栏标题视图:-

    let searchBar: UISearchBar = UISearchBar()
    searchBar.showCancelButton = true
    searchBar.placeholder = "Search Your Job Title"
    searchBar.delegate = self //do not need if you delegate searchBar
    self.navigationItem.titleView = searchBar
    
  2. 将 Bar 按钮拖放到视图控制器的右侧并将其命名为 Cancel。

  3. 然后将该按钮连接到此函数:-

    @IBAction func iPadCancelButton(sender: AnyObject) {
           UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)
          self.dismissViewControllerAnimated(true, completion: nil)
    }
    
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)
        }
    }

根据苹果文档 setShowsCancelButton

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

我不确定替代品,但这就是苹果为我们提供的。

对于使用Xcode11构建的iOS13,我需要手动设置取消按钮上的显示值,具体取决于搜索控制器是否可见