如何在UITableView中实现UISearchController - Swift

42 uitableview uisearchbar ios swift uisearchcontroller

我是Swift的新手,我正在尝试为我UITableViewUIViewController类添加搜索功能.我google了很多,发现UISearchDisplayController已被弃用并被UISearchController取代.当我试图搜索教程时,我没有找到任何特别的UITableView.其中一些是为了实施UITableViewController.所以这是我的问题:

  1. 我们可以实现UISearchControllerUITableView是在一个UIViewController班?(我想我们可以)

  2. 如果可以,请转换用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;
    
    Run Code Online (Sandbox Code Playgroud)

资源

编辑: 我正在尝试将搜索结果更新程序分配为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   
    }
}
Run Code Online (Sandbox Code Playgroud)

*但是在行控制器上.searchResultsUpdater = self我得到了eroor,因为无法将"ViewController"的值分配给类型为" UISearchResultsUpdating?" 的值...所以我真的怀疑我是否可以在UIViewController类型类中使用UISearchController.

And*_*nez 74

是的,搜索工作的方式已根本改变,因为我认为这是一个更好的系统.对于大多数简单的实现,新系统要好得多,直截了当.使用它非常简单.

首先,让你的班级遵守UISearchResultsUpdating协议.

class MyTableViewController: UITableViewController, UISearchResultsUpdating {}

添加搜索控制器属性:

class MyTableViewController: UTableViewController, UISearchResultsUpdating {
    let searchController = UISearchController(searchResultsController: nil)
}
Run Code Online (Sandbox Code Playgroud)

在viewDidLoad中添加搜索栏:

override func viewDidLoad() {
    super.viewDidLoad()

    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.sizeToFit()
    self.tableView.tableHeaderView = searchController.searchBar
}
Run Code Online (Sandbox Code Playgroud)

最后,实现协议的updateSearchResults:for方法UISearchResultsUpdating:

func updateSearchResults(for searchController: UISearchController) {

}
Run Code Online (Sandbox Code Playgroud)

您对此方法的实现当然取决于您从哪里搜索数据.它会在您键入时使用搜索内容更新当前表格视图.确保更新数据源并在updateSearchResultsForSearchController方法中重新加载表视图.同样,它会在您键入时更新,因此请确保如果要搜索的数据很大或者您是从Internet搜索,请在此方法中添加一些并发性.

如果要使用其他控制器来填充搜索结果,则可以在初始化searchController属性时传递该VC .

编辑:我重读了你的问题,看起来我忘了添加一些重要的东西.

UITableViewController有一个名为的成员tableView.您可以获取控制器的表格视图,但要填充您的视图,您UITableView无需触摸它.您不能直接使用UITableView 使用SearchController逻辑.你必须与控制器一起工作才能实现它.使用UITableViewController委托和数据源方法可以使用搜索结果更新表UI.

请继续阅读使用UITableViewController,UITableViewDelegate和UITableViewDataSource,以便了解如何在那里获得搜索结果.


小智 24

如果有人,像我一样吓坏了..这段代码可能有所帮助

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

    }
}
Run Code Online (Sandbox Code Playgroud)