ios 如何在 UITableView 中实现 UISearchController - Swift
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29664315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement UISearchController in UITableView - Swift
提问by Andy Ibanez
I am a newbie to Swift and I am trying to add search functionality to my UITableView
which is in a UIViewController
class. I googled a lot and found that UISearchDisplayController
has been deprecated and replaced by UISearchController. When I tried to search for tutorials I did not find any specifically for UITableView
. Some of them were for implementing in UITableViewController
. So here are my questions:
我是一个新手,斯威夫特和我试图搜索功能添加到我UITableView
这是在一个UIViewController
班。我在谷歌上搜索了很多,发现它UISearchDisplayController
已被弃用并被 UISearchController 取代。当我尝试搜索教程时,我没有找到任何专门针对UITableView
. 其中一些用于在UITableViewController
. 所以这里是我的问题:
Can we implement
UISearchController
in aUITableView
that is in aUIViewController
class? (I guess we can)If we can, please convert these line of codes written in Objective-C. Or if there are some really good tutorials please let me know.
@property (strong, nonatomic) UISearchController *searchController; UITableViewController *searchResultsController = [[UITableViewController alloc] init]; // Init UISearchController with the search results controller self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController]; // Link the search controller self.searchController.searchResultsUpdater = self;
我们可以在类
UISearchController
中的 aUITableView
中实现UIViewController
吗?(我想我们可以)如果可以,请转换这些用 Objective-C 编写的代码行。或者如果有一些非常好的教程,请告诉我。
@property (strong, nonatomic) UISearchController *searchController; UITableViewController *searchResultsController = [[UITableViewController alloc] init]; // Init UISearchController with the search results controller self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController]; // Link the search controller self.searchController.searchResultsUpdater = self;
EDIT :I am trying to assign the search results updater in as
编辑:我正在尝试将搜索结果更新程序分配为
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blackColor()
self.addTableViewWithSection()
self.searchResultsController = UITableViewController()
var controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
}
}
*However on the line controller.searchResultsUpdater = self i get the eroor as Cannot assign a value of typ "ViewController" to a value of type "UISearchResultsUpdating?" .. So i really doubt if i can use UISearchControllerin UIViewControllertype class.
*但是,在 controller.searchResultsUpdater = self 线上,我得到的错误是无法将类型“ViewController”的值分配给“ UISearchResultsUpdating”类型的值?.. 所以我真的怀疑我是否可以在UIViewController类型类中使用UISearchController。
回答by Andy Ibanez
Yes, the way search works has been radically changed for what I consider to be a better system. The new system is much better and straight to the point for most simple implementations. Using it is pretty straightforward.
是的,搜索的工作方式已经彻底改变,我认为这是一个更好的系统。对于大多数简单的实现,新系统要好得多,而且直截了当。使用它非常简单。
First, make your class comply with the UISearchResultsUpdating
protocol.
首先,让你的班级遵守UISearchResultsUpdating
协议。
class MyTableViewController: UITableViewController, UISearchResultsUpdating {}
class MyTableViewController: UITableViewController, UISearchResultsUpdating {}
Add it the search controller property:
将其添加到搜索控制器属性中:
class MyTableViewController: UTableViewController, UISearchResultsUpdating {
let searchController = UISearchController(searchResultsController: nil)
}
Add the search bar in viewDidLoad:
在 viewDidLoad 中添加搜索栏:
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
self.tableView.tableHeaderView = searchController.searchBar
}
And finally, implement the updateSearchResults:for
method that comes from the UISearchResultsUpdating
protocol:
最后,实现updateSearchResults:for
来自UISearchResultsUpdating
协议的方法:
func updateSearchResults(for searchController: UISearchController) {
}
Your implementation of this method will of course depend on where you are searching the data from. It will update your current table view with the contents of your search as you type them. Make sure you update your data source and reload the table view in the updateSearchResultsForSearchController
method. Again, it updates as you type so make sure that if your data to search in is big or if you are searching from the internet, add some concurrency in this method.
您对这种方法的实现当然取决于您从何处搜索数据。它将在您键入搜索内容时更新您当前的表视图。确保更新数据源并在updateSearchResultsForSearchController
方法中重新加载表视图。同样,它会在您键入时更新,因此请确保如果您要搜索的数据很大或者您是从 Internet 搜索,请在此方法中添加一些并发性。
If you want to use a different controller to populate your search results with, you can pass that VC when initialising the searchController
property.
如果您想使用不同的控制器来填充您的搜索结果,您可以在初始化searchController
属性时传递该 VC 。
EDIT: I have reread your question and it looks like I forgot to add something important.
编辑:我已经重读了你的问题,看起来我忘了添加一些重要的东西。
UITableViewController has a member called tableView
. You can grab the controller's table view , but to populate your UITableView
, you don't need to touch it. You can't use the SearchController logic directlywith UITableView. You gotta work with the controller to get it there. Use the UITableViewController delegate and data source methods to get your table UI updated with your search results.
UITableViewController 有一个名为tableView
. 您可以获取控制器的 table view ,但要填充您的UITableView
,您不需要触摸它。你不能直接在 UITableView 中使用 SearchController 逻辑。你必须和控制器一起工作才能到达那里。使用 UITableViewController 委托和数据源方法根据搜索结果更新表格 UI。
Please read on using UITableViewController, UITableViewDelegate, and UITableViewDataSource so you can understand how to get your search results there.
请继续阅读使用 UITableViewController、UITableViewDelegate 和 UITableViewDataSource,以便您了解如何在那里获取搜索结果。
回答by Andy Ibanez
In case of anyone, who is freaking around like me..this code might help
如果有人像我一样疯狂……这段代码可能会有所帮助
class ViewController: UIViewController , UITableViewDataSource, UITableViewDelegate,UISearchResultsUpdating {
@IBOutlet weak var tblView: UITableView!
var tabledata = ["lucques","chickendijon","godaddy","amazon","chris","ambata","bankofamerica","abelcine","AUTO + TRANSPORTATION","BILLS + UTILITIES","FOOD + DINING","HEALTH","AutoCare", "Auto Payment" , "Gas+Fuel","Electric Bill", "Internet/Television","Fast Foodd", "Gorceries" , "Restaurants","Gym Membership", "Health Insurance","auto","note-bullet","knife","heart"]
var filteredTableData = [String]()
var resultSearchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
tblView.delegate = self
tblView.dataSource = self
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
controller.searchBar.barStyle = UIBarStyle.Black
controller.searchBar.barTintColor = UIColor.whiteColor()
controller.searchBar.backgroundColor = UIColor.clearColor()
self.tblView.tableHeaderView = controller.searchBar
return controller
})()
self.tblView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.resultSearchController.active {
return self.filteredTableData.count
}else{
return self.tabledata.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var section = indexPath.section
var row = indexPath.row
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier:"addCategoryCell")
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.backgroundColor = UIColor.clearColor()
cell.contentView.backgroundColor = UIColor.clearColor()
cell.textLabel?.textAlignment = NSTextAlignment.Left
cell.textLabel?.textColor = UIColor.blackColor()
cell.textLabel?.font = UIFont.systemFontOfSize(14.0)
if self.resultSearchController.active {
cell.textLabel?.text = filteredTableData[indexPath.row]
} else {
cell.textLabel?.text = tabledata[indexPath.row]
}
return cell
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)
let array = (tabledata as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tblView.reloadData()
}
}
回答by Bdebeez
For those looking for a bit more context on all the aspects of implementing this, here's a tutorial on how to implement UISearchController
对于那些在实现这一点的所有方面寻找更多上下文的人,这里有一个关于如何实现 UISearchController的教程
In addition to the above answer by Andy Ibanez, you also need to add code to your UITableViewDataSource methods to show the newly filtered results in the tableview.
除了上述 Andy Ibanez 的回答之外,您还需要向 UITableViewDataSource 方法添加代码以在 tableview 中显示新过滤的结果。
Also, don't forget to call tableView.reloadData()
in your updateSearchResults method - the UISearchController does not automatically tell the tableView to reload its data.
另外,不要忘记调用tableView.reloadData()
updateSearchResults 方法 - UISearchController 不会自动告诉 tableView 重新加载其数据。