Chcel by som vedieť, ako zrealizovať vyhľadávaniepanel, ktorý funguje podobne ako panel v aplikácii Instagram. Môj vyhľadávací panel je umiestnený nad UITableView (zoznam priateľov). Aktuálne filtruje zoznam priateľov tak, aby zodpovedal hľadanému výrazu. Mojím cieľom je tiež nechať vyhľadávací panel načítať údaje z môjho servera (Parse) a zobraziť ich pod lokálne hľadanými údajmi.
IE:Vyhľadávanie „Steve“ vráti UITableView všetkých miestnych Steve v zozname priateľov používateľa a ďalších Steve, ktorí sú na serveri, ale s ktorým nie sú priatelia. Potom môže používateľ klepnúť na túto osobu a odoslať jej žiadosť o priateľstvo.
Ako by som mohol dosiahnuť túto funkciu?
odpovede:
1 pre odpoveď č. 1Musíte vytvoriť radič pohľadu (najlepšie a UITableViewController
) ktorý vyhovuje UISearchBarDelegate
, UITableViewDataSource
, a UITableViewDelegate
.
Po správnom nastavení týchto metód protokolu môžete prepínať medzi dvoma zdrojmi údajov, napr NSArray
pre users
a an NSMutableArray
pre searchResults
.
Potom, v UISearchBarDelegate
metódami, môžete aktualizovať searchResults
premenlivé pole s výsledkami predikátu hľadaného textu a obnoviť tableView
dát.
Ak je hľadanie zrušené alebo vymazané, searchResults
by sa mal vrátiť nil
.
V UITableViewDataSource
metód, skontrolujte či searchResults
existuje, a ak áno, načítajte svoje bunky z tohto poľa:
@interface YourViewController () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
/* ... */
@property (nonatomic, strong) NSMutableArray *searchResults;
@property (nonatomic, strong) NSArray *users;
@end
@implementation YourViewControler
/* ... */
- (void)setSearchResults:(NSMutableArray *)searchResults
{
_searchResults = searchResults;
[self.mainView.collectionView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (self.searchResults) {
return self.searchResults.count;
} else {
return users.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
YourTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (self.searchResults) {
/* ... */
} else {
/* ... */
}
return cell;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length > 2) {
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"(user.name CONTAINS[cd] %@) OR (user.username CONTAINS[cd] %@)", searchText, searchText];
self.searchResults = [[self.users filteredArrayUsingPredicate:searchPredicate] mutableCopy];
NSLog(@"Search Result: %@", [self.searchResults valueForKey:@"username"]);
} else if (searchText.length == 0) {
self.searchResults = nil;
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
self.searchResults = nil;
searchBar.text = @"";
[searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
@end