Add a search bar to the iOS table view

Source: Internet
Author: User
Tags uikit

Here's what we want to achieve. This effect is changed on the basis of the previous custom table view.

1. Drag the search bar and search display to the Viewcontroller. Do not add search Bar.

2. Modify the Viewcontroller header file

CPP Code
    1. #import <UIKit/UIKit.h>
    2. @interface Ikrboyviewcontroller4:uiviewcontroller
    3. {
    4. Nsarray *dataarr; //To display data for a table view
    5. Nsarray *alldataarr; //Store all data and assign search results to Dataarr by keyword search
    6. }
    7. @property (Weak, nonatomic) Iboutlet Uisearchbar *searchbar;
    8. @end
#import <UIKit/UIKit.h> @interface ikrboyviewcontroller4:uiviewcontroller{    nsarray *dataarr;//data for displaying table views    Nsarray *alldataarr;//stores all data and assigns search results to Dataarr} @property (weak, nonatomic) Iboutlet uisearchbar *searchbar by keyword search ; @end

3. Modify the custom method Inittableviewdata. Hiding Scopebar is an issue that takes into account the iphone's display height. may be determined at its discretion.

CPP Code
  1. -(void) inittableviewdata{
  2. NSBundle *bundle = [NSBundle mainbundle];
  3. NSString *plistpath = [bundle pathforresource:@"User_head" oftype:@ "plist"];
  4. Alldataarr = [[Nsarray alloc] initwithcontentsoffile:plistpath];
  5. Dataarr = [Nsarray Arraywitharray:alldataarr];
  6. NSLog (@"table data Count =%d", [Alldataarr Count]);
  7. //Set Search bar Scopebar Hide
  8. [Self.searchbar Setshowsscopebar:no];
  9. [Self.searchbar SizeToFit];
  10. }
-(void) inittableviewdata{    nsbundle *bundle = [NSBundle mainbundle];    NSString *plistpath = [Bundle pathforresource:@ "User_head" oftype:@ "plist"];    Alldataarr = [[Nsarray alloc] initwithcontentsoffile:plistpath];    Dataarr = [Nsarray Arraywitharray:alldataarr];    NSLog (@ "table data Count =%d", [Alldataarr Count]);        Set the search bar Scopebar hide    [Self.searchbar setshowsscopebar:no];    [Self.searchbar SizeToFit];}

4. Add three event triggers for Searchbar

CPP Code
  1. The following three methods implement the search function of Searchbar
  2. Reload message to Table view data source when text content changes
  3. -(BOOL) Searchdisplaycontroller: (Uisearchdisplaycontroller *) controller shouldreloadtableforsearchstring: ( NSString *) SearchString
  4. {
  5. [Self filtercontentforsearchtext:searchstring scope:self.searchBar.selectedScopeButtonIndex];
  6. //yes case The table view can be Reloaded
  7. return YES;
  8. }
  9. Reload message to Table view data source when scope bar chooses to send changes
  10. -(BOOL) Searchdisplaycontroller: (Uisearchdisplaycontroller *) controller shouldreloadtableforsearchscope: ( Nsinteger) SearchOption
  11. {
  12. [Self filterContentForSearchText:self.searchBar.text scope:searchoption];
  13. //Yes Case table view can be Reloaded
  14. return YES;
  15. }
  16. Click the Cancel button for the event
  17. -(void) searchbarcancelbuttonclicked: (Uisearchbar *) Searchbar
  18. {
  19. //Query all
  20. [Self filtercontentforsearchtext:@"" scope:-1];
  21. }
The following three methods implement Searchbar's search function//When the text content changes, issue a reload message to the table view data source-(BOOL) Searchdisplaycontroller: (Uisearchdisplaycontroller *) Controller shouldreloadtableforsearchstring: (NSString *) searchstring{    [self filtercontentforsearchtext: SearchString Scope:self.searchBar.selectedScopeButtonIndex];    Yes, the table view can reload    return yes; Reload message to Table view data source when the scope bar chooses to send changes-(BOOL) Searchdisplaycontroller: (Uisearchdisplaycontroller *) controller Shouldreloadtableforsearchscope: (Nsinteger) searchoption{    [self filtercontentforsearchtext: Self.searchBar.text Scope:searchoption];    Yes, the table view can reload    return yes; Click the Cancel button event-(void) searchbarcancelbuttonclicked: (Uisearchbar *) searchbar{    //query all    [self filtercontentforsearchtext:@ "" Scope:-1];}

5. Custom keyword search function

CPP Code
  1. A custom search method that searches from Alldataarr for elements that satisfy the search criteria and assigns the matched array to Dataarr, because Dataarr is the data source for the table view, so the table view's records change accordingly.
  2. -(void) Filtercontentforsearchtext: (nsstring*) searchtext scope: (nsuinteger) scope;
  3. {
  4. if ([SearchText length]==0)
  5. {
  6. //Query all
  7. Dataarr = [Nsarray Arraywitharray:alldataarr];
  8. NSLog (@"dataarr count =%d", [Dataarr Count]);
  9. return;
  10. }
  11. Nspredicate *scopepredicate;
  12. switch (scope) {
  13. Case 0:
  14. Scopepredicate = [Nspredicate predicatewithformat:@"(Self.itemname contains[c]%@) OR (Self.itemimagepath contains  [C]%@) ", Searchtext,searchtext];
  15. NSLog (@"searchtext=%@", SearchText);
  16. Dataarr =[nsarray Arraywitharray:[alldataarr Filteredarrayusingpredicate:scopepredicate];
  17. Break ;
  18. Case 1:
  19. Scopepredicate = [nspredicate predicatewithformat:@"Self.itemname contains[c]%@", SearchText];
  20. Dataarr = [Nsarray arraywitharray:[alldataarr filteredarrayusingpredicate:scopepredicate]];
  21. Break ;
  22. Case 2:
  23. Scopepredicate = [nspredicate predicatewithformat:@"Self.itemimagepath contains[c]%@", SearchText];
  24. Dataarr =[nsarray Arraywitharray:[alldataarr Filteredarrayusingpredicate:scopepredicate];
  25. Break ;
  26. }
  27. }
A custom search method that searches from Alldataarr for elements that satisfy the search criteria and assigns the matched array to Dataarr, because Dataarr is the data source for the table view, so the table view's records change accordingly. -(void) Filtercontentforsearchtext: (nsstring*) searchtext scope: (nsuinteger) scope;        {if ([SearchText length]==0) {//query all Dataarr = [Nsarray Arraywitharray:alldataarr];        NSLog (@ "Dataarr count =%d", [Dataarr Count]);    Return        } nspredicate *scopepredicate; Switch (scope) {Case 0:scopepredicate = [Nspredicate predicatewithformat:@ "(Self.itemname Contains[c]            %@) OR (Self.itemimagepath contains[c]%@) ", Searchtext,searchtext];            NSLog (@ "searchtext=%@", SearchText);            Dataarr =[nsarray Arraywitharray:[alldataarr Filteredarrayusingpredicate:scopepredicate];        Break            Case 1:scopepredicate = [nspredicate predicatewithformat:@ "Self.itemname contains[c]%@", SearchText];            Dataarr = [Nsarray arraywitharray:[alldataarr filteredarrayusingpredicate:scopepredicate]];        Break CASE 2:scopepredicate = [nspredicate predicatewithformat:@ "Self.itemimagepath contains[c]%@", SearchText];            Dataarr =[nsarray Arraywitharray:[alldataarr Filteredarrayusingpredicate:scopepredicate];    Break }}

6. Modify the Cellforrowatindexpath method

CPP Code
  1. -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath
  2. {
  3. static NSString *cellidentifier = @"Mytablecell";
  4. Mytableviewcell *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier];
  5. //add code begin:important,for showing searching results
  6. //Do not judge the cell null value, will result in the search, can not find the corresponding identifier cell and error.
  7. if (cell = = nil) {
  8. //Search results using a simple table view cell's style, not a custom table view cell's style
  9. cell = [[Mytableviewcell alloc] Initwithstyle:uitableviewcellstylesubtitle reuseidentifier:cellidentifier];
  10. Nsuinteger row = [Indexpath row];
  11. Nsdictionary *rowdict = [Dataarr objectatindex:row];
  12. Cell.textLabel.text = [rowdict objectforkey:@"ItemName"];
  13. NSString *imagepath = [rowdict objectforkey:@"Itemimagepath"];
  14. Cell.imageView.image = [UIImage Imagenamed:imagepath];
  15. }
  16. //add code End
  17. Nsuinteger row = [Indexpath row];
  18. Nsdictionary *rowdict = [Dataarr objectatindex:row];
  19. Cell.label.text = [rowdict objectforkey:@"ItemName"];
  20. NSLog (@"Cell.label.text =%@", [rowdict objectforkey:@"ItemName"]);
  21. NSString *imagepath = [rowdict objectforkey:@"Itemimagepath"];
  22. Cell.image.image = [UIImage Imagenamed:imagepath];
  23. NSLog (@"cell.image.image =%@", ImagePath);
  24. Cell.accessorytype = Uitableviewcellaccessorydisclosureindicator;
  25. return cell;
  26. }
-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{static    NSString *cellidentifier = @ "Mytablecell";    Mytableviewcell *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier];    Add code begin:important,for showing searching results//does not determine the cell null value, will cause the search, the corresponding identifier can not find the cell and error. if (cell = = nil) {//Search results using a simple table view cell's style, not a custom table view cell's style cell = [[Mytableviewcell alloc] Initwithstyle:uit        Ableviewcellstylesubtitle Reuseidentifier:cellidentifier];        Nsuinteger row = [Indexpath row];        Nsdictionary *rowdict = [Dataarr objectatindex:row];        Cell.textLabel.text = [rowdict objectforkey:@ "ItemName"];        NSString *imagepath = [rowdict objectforkey:@ "Itemimagepath"];    Cell.imageView.image = [UIImage Imagenamed:imagepath];    }//add code end Nsuinteger row = [Indexpath row];    Nsdictionary *rowdict = [Dataarr objectatindex:row]; Cell.label.text = [Rowdict Objectforkey:@ "ItemName"];        NSLog (@ "Cell.label.text =%@", [rowdict objectforkey:@ "ItemName"]);    NSString *imagepath = [rowdict objectforkey:@ "Itemimagepath"];    Cell.image.image = [UIImage Imagenamed:imagepath];        NSLog (@ "cell.image.image =%@", ImagePath);        Cell.accessorytype = Uitableviewcellaccessorydisclosureindicator; return cell;}

Add a search bar to the iOS table view

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.