ios - How to do searching in NSTableView with NSSearchFiled? -
i have implemented application in use nstableview of data source , delegates have not used nsarraycontroller nor want use it. question how can bind nssearchfield nstableview in situation? had seen lot of answer using nsarraycontroller. not want convert implementation nsarraycontroller things working nsmutablearray.
tableview display control , not filtering. should add 2 nsarray properties;
1) @property(nonatomic, strong) nsarray *allitems;
2) @property(nonatomic, strong) nsarray *filtereditems;
#import "viewcontroller.h" @interface viewcontroller()<nssearchfielddelegate, nstableviewdelegate, nstableviewdatasource> // nssearchfield @property (weak) iboutlet nssearchfield *searchfield; // nstableview @property (weak) iboutlet nstableview *tableview; // in array store items @property(nonatomic, strong) nsarray *allitems; // in array store filtered items @property(nonatomic, strong) nsarray *filtereditems; @end @implementation viewcontroller - (void)viewdidload { [super viewdidload]; self.searchfield.delegate = self;// can set delegate xib/storyboard self.tableview.delegate = self;// can set delegate xib/storyboard self.tableview.datasource = self;// can set datasource xib/storyboard self.allitems = @[@"test1", @"demo filter", @"test 2", @"abracadabra"]; [self applyfilterwithstring:@""]; } - (void)controltextdidchange:(nsnotification *)obj{ if (obj.object == self.searchfield) { [self applyfilterwithstring:self.searchfield.stringvalue]; } } -(void)applyfilterwithstring:(nsstring*)filter { if (filter.length>0) { nspredicate *filterpredicate = [nspredicate predicatewithformat:@"self contains[cd] %@", filter]; self.filtereditems = [self.allitems filteredarrayusingpredicate:filterpredicate]; } else { self.filtereditems = self.allitems.copy; } [self.tableview reloaddata]; } #pragma mark - ***** nstableviewdatasource, nstableviewdelegate ***** - (nsinteger)numberofrowsintableview:(nstableview *)tableview { return self.filtereditems.count; } // "cell based" tableview - (nullable id)tableview:(nstableview *)tableview objectvaluefortablecolumn:(nullable nstablecolumn *)tablecolumn row:(nsinteger)row { nsstring *item = self.filtereditems[row]; return item; } @end
Comments
Post a Comment