Xamarin.iOS: Applying Search Bar In TableView

In this article, we will see how we can add a search bar to the TableView control. TableView is a very important and most widely used control. Thus, we will be having a lot of the tutorials that focus on the different aspects of it. This is the third one of the TableView series. The others are: 
Ingredients
  • Visual Studio 2012 or higher / Xamarin Studio 5.
  • Xamarin iOS 6.4.5 or higher.
  • Mac OS X Yosemite(10.10) & above.

Procedure

  1. Create a new Application in Xamarin Studio by selecting New Solution from the welcome screen.

    welcome

  2. Select iOS app from the installed templates. Now, as you can see, we have a lot of options, like Single View app, Master-Detail app, Tabbed app. These are nothing but pre-defined UI screens for the ease-of-use of the developers. For this tutorial, we will select Single View app.

    Single View

  3. Now, we will name the app and select the minimum iOS version that our app will support, as shown here.

    version

  4. Now, we will name the project, give the location for the solution to be saved, and select the version control for git (if required), as shown below:

    location

  5. Now, we can see that the solution file is created and it contains all the required files, as shown below.

    solution

  6. Now, we will open ViewController.cs from the solution and import CoreGraphics, System, System.Collections.Generic, and UIKit. 
    1. using System;  
    2. using CoreGraphics;  
    3. using System.Collections.Generic;  
    4. using UIKit;  
  7.  Create an object of UITableView, TableSource, UISearchBar and List<TableItem> in the ViewController class. 
    1. UITableView table;  
    2. TableSource tableSource;  
    3. List<TableItem> tableItems;  
    4. UISearchBar searchBar;  
  8. To set the title of the app in the ViewDidLoad function, just write the following:
    1. Title = "SearchBarWithTableView Sample";  
  9. Now, we will add the TableView properties in the ViewDidLoad function. Also, add the TableView to the View and the SearchBar to the TableHeaderView. Finally, our ViewDidLoad() will look, as given below: 
    1. protected ViewController(IntPtr handle) : base(handle)  
    2.         {  
    3.             // Note: this .ctor should not contain any initialization logic.  
    4.         }  
    5.   
    6.         public override void ViewDidLoad()  
    7.         {  
    8.             base.ViewDidLoad();  
    9.             // Perform any additional setup after loading the view, typically from a nib.  
    10.   
    11.             //Declare the search bar and add it to the header of the table  
    12.             searchBar = new UISearchBar();  
    13.             searchBar.SizeToFit();  
    14.             searchBar.AutocorrectionType = UITextAutocorrectionType.No;  
    15.             searchBar.AutocapitalizationType = UITextAutocapitalizationType.None;  
    16.             searchBar.TextChanged += (sender, e) =>  
    17.             {  
    18.                 //this is the method that is called when the user searches  
    19.                 searchTable();  
    20.             };  
    21.   
    22.             Title = "SearchBarWithTableView Sample";  
    23.             table = new UITableView(new CGRect(0, 20, View.Bounds.Width, View.Bounds.Height - 20));  
    24.             //table.AutoresizingMask = UIViewAutoresizing.All;  
    25.             tableItems = new List<TableItem>();  
    26.   
    27.             tableItems.Add(new TableItem("Vegetables") { ImageName = "Vegetables.jpg" });  
    28.             tableItems.Add(new TableItem("Fruits") { ImageName = "Fruits.jpg" });  
    29.             tableItems.Add(new TableItem("Flower Buds") { ImageName = "Flower Buds.jpg" });  
    30.             tableItems.Add(new TableItem("Legumes") { ImageName = "Legumes.jpg" });  
    31.             tableItems.Add(new TableItem("Tubers") { ImageName = "Tubers.jpg" });  
    32.             tableSource = new TableSource(tableItems);  
    33.             table.Source = tableSource;  
    34.             table.TableHeaderView = searchBar;  
    35.             Add(table);  
    36.         }  
  10. We also add the searchTable() method for the UISearchBar to perform the search action.
    1. private void searchTable()  
    2.         {  
    3.             //perform the search, and refresh the table with the results  
    4.             tableSource.PerformSearch(searchBar.Text);  
    5.             table.ReloadData();  
    6.         }  
  11. Now, we will add a new class, TableSource, to the solution.

    class

  12. Once the file is added, open TableSource.cs and add the code, as given below: 
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.IO;  
    4. using System.Linq;  
    5. using Foundation;  
    6. using UIKit;  
    7.   
    8. namespace SearchBarWithTableView  
    9. {  
    10.     public class TableSource : UITableViewSource  
    11.     {  
    12.         private List<TableItem> tableItems = new List<TableItem>();  
    13.         private List<TableItem> searchItems = new List<TableItem>();  
    14.         protected string cellIdentifier = "TableCell";  
    15.   
    16.         public TableSource(List<TableItem> items)  
    17.         {  
    18.             this.tableItems = items;  
    19.             this.searchItems = items;  
    20.         }  
    21.   
    22.         public override nint RowsInSection(UITableView tableview, nint section)  
    23.         {  
    24.             return searchItems.Count;  
    25.         }  
    26.   
    27.         public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)  
    28.         {  
    29.             // request a recycled cell to save memory  
    30.             UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);  
    31.   
    32.   
    33.             var cellStyle = UITableViewCellStyle.Default;  
    34.   
    35.             // if there are no cells to reuse, create a new one  
    36.             if (cell == null)  
    37.             {  
    38.                 cell = new UITableViewCell(cellStyle, cellIdentifier);  
    39.             }  
    40.   
    41.             cell.TextLabel.Text = searchItems[indexPath.Row].Title;  
    42.             cell.ImageView.Image = UIImage.FromFile("Images/" + searchItems[indexPath.Row].ImageName);  
    43.   
    44.             return cell;  
    45.         }  
    46.   
    47.         public override nint NumberOfSections(UITableView tableView)  
    48.         {  
    49.             return 1;  
    50.         }  
    51.   
    52.         public void PerformSearch(string searchText)  
    53.         {  
    54.             searchText = searchText.ToLower();  
    55.             this.searchItems = tableItems.Where(x => x.Title.ToLower().Contains(searchText)).ToList();  
    56.         }  
    57.     }  
    58. }  
    This class is used to implement the abstract class UITableViewSource. Thus, we define the basic functions required for a TableView. RowsInSection is used to determine the number of rows present in a section; NumberOfSections are used to determine the number of sections; the TableView is divided and the GetCell defines the UITableViewCell that will be rendered for a particular row. We also add methods which help in depicting the Search in action by adding a PerformSearch() method.
  13. Now, we will add another class, TableItem, to the solution, for the customized cell style. Once the file is added, open TableItem.cs and add the code, as given below: 
    1. using System;  
    2. using UIKit;  
    3.   
    4. namespace SearchBarWithTableView  
    5. {  
    6.     public class TableItem  
    7.     {  
    8.         public string Title { getset; }  
    9.   
    10.         public string ImageName { getset; }  
    11.   
    12.         public UITableViewCellStyle CellStyle  
    13.         {  
    14.             get { return cellStyle; }  
    15.             set { cellStyle = value; }  
    16.         }  
    17.         protected UITableViewCellStyle cellStyle = UITableViewCellStyle.Default;  
    18.   
    19.         public UITableViewCellAccessory CellAccessory  
    20.         {  
    21.             get { return cellAccessory; }  
    22.             set { cellAccessory = value; }  
    23.         }  
    24.         protected UITableViewCellAccessory cellAccessory = UITableViewCellAccessory.None;  
    25.   
    26.         public TableItem() { }  
    27.   
    28.         public TableItem(string title)  
    29.         { Title = title; }  
    30.   
    31.     }  
    32. }  
  14. Now, we run the app on the iPhone simulator of our choice (I did it on iPhone 4S) and it looks, as shown below.

    simulator

  15. Start typing the word that you want to search.

    search                                                                                                 
Make some beautiful apps using Xamarin.iOS and tweet your queries to @adiiaditya. If you want to fork this project, visit my Git.

Up Next
    Ebook Download
    View all
    Learn
    View all