取消按钮未显示在UISearchBar中

时间:2015-05-27 06:15:19

标签: ios objective-c uisearchbar uisearchcontroller

我有UICollectionView。点击UINavigationBar中的搜索按钮,我将UISearchController的{​​{1}}添加为searchbar的标题视图。对于iPhone它运作正常。对于iPad,未显示UINavigationItem按钮。单独的搜索栏占据整个宽度。

enter image description here

任何人都可以帮我解决这个问题吗?提前谢谢。

7 个答案:

答案 0 :(得分:18)

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

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

答案 1 :(得分:7)

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

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

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

答案 2 :(得分:2)

试试这个。为节目取消按钮添加复选标记。

enter image description here

答案 3 :(得分:2)

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)
        }
    }

答案 4 :(得分:1)

Swift版本: -

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

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按钮拖放到视图控制器右侧;将其命名为取消。

  3. 然后将该按钮连接到此功能: -

    @IBAction func iPadCancelButton(sender: AnyObject) {
           UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)
          self.dismissViewControllerAnimated(true, completion: nil)
    }
    

答案 5 :(得分:1)

根据Apple文档setShowsCancelButton

  

在iPad上运行的应用程序不显示取消按钮,即使在   您可以为showsCancelButton参数指定“是”。

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

enter image description here

答案 6 :(得分:0)

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