您好,我正在尝试使用UISearchBar筛选用户的搜索。.我的用户列表位于Firebase的RealTimeDatabase中。
我在tableviewcontroller中向用户显示的方式是:
现在我的问题是,如果用户使用UISearchBar,我不知道如何实现过滤数据的功能,你们中的任何一个可以帮助我解决此问题吗?
在下部,我向您展示了从数据库中查询数据以及实现搜索栏过滤器的方式..当然,我过滤数据的方式是错误的,我无法弄清楚哪里出了问题..我尝试了很多方法,但我无法解决...
@interface UserSearchViewController () <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *users;
@property (nonatomic, strong) NSMutableArray *filteredUsers;
@property (nonatomic, assign) BOOL isFiltered;
@property (nonatomic, strong) UserHandler *user;
- (void)viewDidLoad {
[super viewDidLoad];
/// Prepariamo la MutableArray che contiene i dati degli user
_users = NSMutableArray.new;
_searchBar.delegate = self;
[self setupTableView];
[self retrieveAllUser];
}
#pragma mark - Search Bar Filter Data
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[self filteredContent:searchText];
[self.tableView reloadData];
}
-(void)filteredContent:(NSString *)searchText {
if (searchText.length == 0) _isFiltered = NO;
else {
_isFiltered = YES;
_filteredUsers = NSMutableArray.new;
for (NSString *str in self.users) {
NSRange range = [self.user.name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) [self.filteredUsers addObject:str];
}
}
}
#pragma mark - User Query
-(void)retrieveAllUser {
/// Creiamo una referenza al Database di Firebase
FIRDatabaseReference *dbRef = FIRDatabase.database.reference;
/// Effettuiamo la query
[[[dbRef child:kUserAccFolder] queryOrderedByChild:kUserAccEmail] observeEventType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot *snapshot) {
NSDictionary *dict = snapshot.value;
if (dict) {
self.user = UserHandler.new;
self.user.name = dict[kUserAccName];
self.user.university = dict [kUserAccUniversity];
self.user.photoProfileURL = dict [kUserAccUrlImage];
self.user.userID = snapshot.key;
[self.users addObject:self.user];
}
[self.tableView reloadData];
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_isFiltered) return self.filteredUsers.count;
return self.users.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UserSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
self.user = _isFiltered ? self.filteredUsers[indexPath.row] : self.users[indexPath.row];
cell.name.text = self.user.name;
return cell;
}