2015-10-20 79 views
3

我试图隐藏取消在UISearchController搜索栏的按钮,但不幸的是设定的viewDidLoad以下()不工作:隐藏取消按钮上的搜索栏在UISearchController

override func viewDidLoad() { 
    super.viewDidLoad() 

    searchResultsTableController = UITableViewController() 
    searchResultsTableController.tableView.delegate = self 

    searchController = UISearchController(searchResultsController: searchResultsTableController) 
    searchController.searchResultsUpdater = self 
    searchController.searchBar.sizeToFit() 
    searchResultsView.tableHeaderView = searchController.searchBar 

    searchController.delegate = self 
    searchController.dimsBackgroundDuringPresentation = false 
    searchController.searchBar.delegate = self 

    searchController.searchBar.searchBarStyle = .Minimal 
    searchController.searchBar.showsCancelButton = false 

    definesPresentationContext = true 
} 

我有在此委托方法使用上面的代码也试过:

func didPresentSearchController(searchController: UISearchController) { 
    searchController.searchBar.showsCancelButton = false 
} 

这种方法工作,但会隐藏它,这是不理想的前短暂显示的取消按钮。有什么建议么?

+0

您可以详细了解您的实现?你在哪里放了searchController.searchBar.showsCancelButton = false –

回答

15

我结束了两个子类和UISearchBarUISearchController建议:

CustomSearchBar.swift

import UIKit 

class CustomSearchBar: UISearchBar { 

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

CustomSearchController.swift

import UIKit 

class CustomSearchController: UISearchController, UISearchBarDelegate { 

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

     return result 
    }() 

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

感谢您发布此解决方案。我将为此提供一个雷达,正如人们所期望的那样,setShowsCancelButton将使用工厂对象在整个对象的生命周期中保持一致。 – Adrian

+0

提起的雷达#29859105 – Adrian

+2

我在Swift 3和iOS 10上,这几乎可以工作。相反,我尝试了[这个线程](http://stackoverflow.com/a/42029836/851515)的其他答案,并得到了一个结果。 不是重写'layoutSubviews',而是重写'setShowsCancelButton(:animated:)'。 –

1

隐藏在搜索栏委托方法的取消按钮和设置您的委托searchController.searchBar.delegate=selfUISearchBarDelegate

func searchBarTextDidBeginEditing(searchBar: UISearchBar) { 

} 

func searchBarTextDidEndEditing(searchBar: UISearchBar) { 

} 
+0

不幸的是,这不起作用。取消按钮仍然显示不受影响。 – Griffith

+0

你是否正确设置了代理,检查代理func是否被调用?它在ma结束工作 – Mukesh

+0

这不起作用 – aneuryzm

0

尝试继承UISearchBar和实施:

override func layoutSubviews() { 
    super.layoutSubviews() 
    self.setShowsCancelButton(false, animated: false) 
} 

SO thread可以帮助您更在这个方向。

相关问题