tutorial searchcontroller bar ios uitableview swift uisearchbar uisearchcontroller

ios - bar - Cómo implementar UISearchController en UITableView-Swift



uisearchcontroller tableview (3)

En el caso de alguien, que está volviendo loco como yo ... este código podría ayudar

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

Soy un novato en Swift y estoy tratando de agregar funcionalidad de búsqueda a mi UITableView que está en una clase UIViewController . Busqué en Google y descubrí que UISearchDisplayController ha sido desaprobado y reemplazado por UISearchController. Cuando traté de buscar tutoriales, no encontré ninguno específicamente para UITableView . Algunos de ellos fueron para implementar en UITableViewController . Asi que aqui están mis preguntas:

  1. ¿Podemos implementar UISearchController en una UITableView que está en una clase UIViewController ? (Creo que podemos)

  2. Si podemos, convierta esta línea de códigos escrita en Objective-C. O si hay algunos tutoriales realmente buenos, házmelo saber.

    @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;

Source

EDITAR: estoy intentando asignar el actualizador de resultados de búsqueda como

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

* Sin embargo, en la línea controller.searchResultsUpdater = self, obtengo el error, ya que no puedo asignar un valor de tipo "ViewController" a un valor de tipo " UISearchResultsUpdating ?" Así que realmente dudo si puedo usar UISearchController en la clase de tipo UIViewController .


Para aquellos que buscan un poco más de contexto en todos los aspectos de la implementación de esto, aquí hay un tutorial sobre cómo implementar UISearchController

Además de la respuesta anterior de Andy Ibáñez , también necesita agregar código a sus métodos UITableViewDataSource para mostrar los resultados recientemente filtrados en la tabla vista.

Además, no olvides llamar a tableView.reloadData() en tu método updateSearchResults - UISearchController no le dice automáticamente a tableView que vuelva a cargar sus datos.


Sí, la forma en que funciona la búsqueda ha cambiado radicalmente para lo que considero un mejor sistema. El nuevo sistema es mucho mejor y directo al punto para la mayoría de las implementaciones simples. Usarlo es bastante sencillo.

Primero, haga que su clase cumpla con el protocolo UISearchResultsUpdating .

class MyTableViewController: UITableViewController, UISearchResultsUpdating {}

Agregue la propiedad del controlador de búsqueda:

class MyTableViewController: UTableViewController, UISearchResultsUpdating { let searchController = UISearchController(searchResultsController: nil) }

Agregue la barra de búsqueda en viewDidLoad:

override func viewDidLoad() { super.viewDidLoad() searchController.searchResultsUpdater = self searchController.hidesNavigationBarDuringPresentation = false searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.sizeToFit() self.tableView.tableHeaderView = searchController.searchBar }

Y finalmente, implemente updateSearchResults:for método que proviene del protocolo UISearchResultsUpdating :

func updateSearchResults(for searchController: UISearchController) { }

La implementación de este método dependerá, por supuesto, de dónde busque los datos. Actualizará su vista de tabla actual con los contenidos de su búsqueda a medida que los escribe. Asegúrese de actualizar su fuente de datos y vuelva a cargar la vista de tabla en el método updateSearchResultsForSearchController . De nuevo, se actualiza a medida que escribe, así que asegúrese de que si sus datos para buscar son grandes o si está buscando desde Internet, agregue algo de simultaneidad en este método.

Si desea utilizar un controlador diferente para completar sus resultados de búsqueda, puede pasar ese CV al inicializar la propiedad searchController .

EDITAR : He vuelto a leer tu pregunta y parece que olvidé agregar algo importante.

UITableViewController tiene un miembro llamado tableView . Puede tomar la vista de tabla del controlador, pero para llenar su UITableView , no necesita tocarlo. No puede usar la lógica SearchController directamente con UITableView. Tienes que trabajar con el controlador para llevarlo allí. Use el delegado UITableViewController y los métodos de fuente de datos para actualizar su UI de tabla con sus resultados de búsqueda.

Siga leyendo con UITableViewController, UITableViewDelegate y UITableViewDataSource para que pueda entender cómo obtener los resultados de su búsqueda allí.