iphone - Search bar filter not working -
i creating search bar filter pragmatically, sadly not working. believe missing minor detail.the table view working correctly not search bar filter.i not using story board nor xib files project.
.h
uisearchbar *searchbar; nsmutablearray * getterms; @property (strong, nonatomic) nsmutablearray* alltabledata; @property (strong, nonatomic) nsmutablearray* filteredtabledata; @property (nonatomic, retain) uitableview *tableview; @property (nonatomic, assign) bool isfiltered;
.m
-(void)viewdidload{ searchbar.delegate = self; searchbar = [[uisearchbar alloc] initwithframe:cgrectmake(30, 10, 750, 31)]; searchbar.placeholder = @"search"; //place holder searchbar.backgroundcolor = [uicolor whitecolor]; searchbar.autocorrectiontype = uitextautocorrectiontypeno; searchbar.backgroundcolor = [uicolor clearcolor]; searchbar.keyboardtype = uikeyboardtypedefault; self.navigationitem.titleview = searchbar; searchbar.layer.cornerradius = 5; searchbar.layer.maskstobounds = yes; uitableview *tableview = [[uitableview alloc] initwithframe:cgrectmake(10.0, 10.0, 1000.0, 200.0) style:uitableviewstyleplain]; self.tableview = tableview; [self.view addsubview:tableview]; self.tableview.datasource = self; } -(void)searchbar:(uisearchbar*)searchbar textdidchange:(nsstring*)text { if(text.length == 0) { isfiltered = false; } else { isfiltered = true; filteredtabledata = [[nsmutablearray alloc] init]; (food* food in alltabledata) { nsrange namerange = [food.name rangeofstring:text options:nscaseinsensitivesearch]; nsrange descriptionrange = [food.description rangeofstring:text options:nscaseinsensitivesearch]; if(namerange.location != nsnotfound || descriptionrange.location != nsnotfound) { [filteredtabledata addobject:food]; } } } [self.tableview reloaddata]; } - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *mycellidentifier = @"mycellidentifier"; uitableviewcell *cell = [self.tableview dequeuereusablecellwithidentifier:mycellidentifier]; if (cell == nil) cell = [[uitableviewcell alloc] initwithstyle:uitableviewcellstylesubtitle reuseidentifier:mycellidentifier]; food* food; if(isfiltered) food = [filteredtabledata objectatindex:indexpath.row]; else food = [alltabledata objectatindex:indexpath.row]; cell.textlabel.text = food.name; cell.detailtextlabel.text = food.description; return cell; } - (nsinteger)numberofsectionsintableview:(uitableview *)tableview { return 1; } - (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section { int rowcount; if(self.isfiltered) rowcount = filteredtabledata.count; else rowcount = alltabledata.count; return rowcount; }
searchbar.delegate = self;
is before searchbar allocation. move below:
searchbar = [[uisearchbar alloc] initwithframe:cgrectmake(30, 10, 750, 31)]; searchbar.delegate = self;
Comments
Post a Comment