使用动态生成的数组使用搜索栏



我想使用搜索栏,其中元素在服务的帮助下动态生成。就像,如果我将" i"作为参数传递,那么服务将获取所有包含" i"作为初始字符的元素。我无法将逻辑检索为如何在代码中实现该逻辑。

下面是用于获取数据的服务。但是我不知道如何使用它实现搜索栏。

NSURL * url=[NSURL URLWithString:@"http://dealnxt.com/api/search?searchkey=i"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"Array is:%@",array);

在我尝试的代码下方:

.h文件

#import <UIKit/UIKit.h>
@interface SearchViewController : UIViewController<UISearchDisplayDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate>
{
    NSMutableArray *contentList;
    NSMutableArray *filteredContentList;
    BOOL isSearching;
}
@property (strong, nonatomic) IBOutlet UIView *SearchView;
@property (strong, nonatomic) IBOutlet UISearchBar *SearchBar;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *Search;
@property (strong, nonatomic) IBOutlet UITableView *Content;
@end

.m文件

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
 }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (isSearching) {
    return [filteredContentList count];
}
else {
    return [contentList count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (isSearching) {
    cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else {
    cell.textLabel.text = [[contentList objectAtIndex:indexPath.row] valueForKey:@"shortdescription"];
}
return cell;
}
- (void)searchTableList {
NSString *searchString = _SearchBar.text;
NSString *UrlString =[NSString stringWithFormat:@"http://dealnxt.com/api/search?searchkey=%@",searchString];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:[NSURL URLWithString:UrlString]];
[Request setHTTPMethod:@"GET"];
NSData *ReturnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
contentList=[jsonDict objectForKey:@"ProductDescriptionModel"];
    [filteredContentList addObject:[[contentList firstObject] valueForKey:@"shortdescription"]];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(@"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
if([searchText length] != 0) {
    isSearching = YES;
    [self searchTableList];
}
else {
    isSearching = NO;
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Search Clicked");
[self searchTableList];
}

这是解决方案:

.h文件 #import

@interface SearchViewController : UIViewController<UISearchDisplayDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate>
{
   NSMutableArray *contentList;
   NSMutableArray *filteredContentList;
   BOOL isSearching;
}
@property (strong, nonatomic) IBOutlet UIView *SearchView;
@property (strong, nonatomic) IBOutlet UISearchBar *SearchBar;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *Search;
@property (strong, nonatomic) IBOutlet UITableView *Content;
@end

.m文件

 #import "SearchViewController.h"
 #import "UIColor+HexString.h"
 @interface SearchViewController ()
 @end
 @implementation SearchViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    _SearchView.backgroundColor=[UIColor colorWithHexString:@"#5130F7"];
   _SearchBar.barTintColor=[UIColor colorWithHexString:@"#5130F7"];
   _SearchBar.layer.borderWidth = 1;
   _SearchBar.layer.borderColor = [UIColor colorWithHexString:@"#5130F7"].CGColor;
   _Content.delegate=self;
   _Content.dataSource=self;
  }
 - (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
 }
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
     return 1;
  }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   if (isSearching) {
    return [filteredContentList count];
}
  else {
    return [contentList count];
}
}
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (isSearching) {
    cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else {
    cell.textLabel.text = [[contentList objectAtIndex:indexPath.row] valueForKey:@"shortdescription"];
}
return cell;
}
- (void)searchTableList {
NSString *searchString = _SearchBar.text;
NSString *UrlString =[NSString stringWithFormat:@"http://abc.in/key?key=%@",searchString];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:[NSURL URLWithString:UrlString]];
[Request setHTTPMethod:@"GET"];
NSData *ReturnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
contentList=[jsonDict objectForKey:@"ProductDescriptionModel"];
filteredContentList =[contentList valueForKey:@"shortdescription"];

NSLog(@"filter:%@",filteredContentList);
[_Content reloadData];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(@"Text change - %d",isSearching);
//[filteredContentList removeAllObjects];
if([searchText length] != 0) {
    isSearching = YES;
    [self searchTableList];
}
else {
    isSearching = NO;
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Search Clicked");
[self searchTableList];
}
 @end

搜索从动态数组中搜索任何内容的简便方法

您的控制器.m

{
NSMutableArray *contacts;
NSMutableArray *combinearray;
NSString *searchTextString;
NSMutableArray *searchArray;
BOOL isFilter;
}

- (void)viewDidLoad {
[super viewDidLoad];
txtSearchBar.backgroundColor=Clear;
txtSearchBar.layer.cornerRadius=2;
txtSearchBar.clipsToBounds=YES;
txtSearchBar.delegate =self;
txtSearchBar.layer.borderColor=Black.CGColor;
txtSearchBar.layer.borderWidth=2.0f;
[txtSearchBar addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
txtSearchBar.layer.sublayerTransform = CATransform3DMakeTranslation(20, 0, 0);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.

if(isFilter)
{
    return [searchArray count];
}
else
return  arrCardsName.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(isFilter)
{
yourDictionary = [searchArray objectAtIndex:indexPath.row];
}
else
{
yourDictionary = [yourArray objectAtIndex:indexPath.row];
}
return cell;
}

-(void)textFieldDidChange:(UITextField*)textField
{
searchTextString = textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText
{
if (searchText.length > 0)
{
    isFilter=YES;
    searchArray = [NSMutableArray array];
    searchText = [NSString stringWithFormat:@"%@",searchText];

    for ( NSDictionary* item in yourArray )
    {
        //NSLog(@"contacts ----->%@",[item objectForKey:@"city"]);
        if ([[[item objectForKey:@"city"] lowercaseString] rangeOfString:[searchText lowercaseString]].location != NSNotFound)//object for key @"do whatever you want to search"
        {
            [searchArray addObject:item];
        }
    }

}
if (!searchText || searchText.length == 0)
{
    isFilter=NO;
    searchArray = [yourArray mutableCopy];
}
else
{
    if ([searchArray count] == 0)
    {
        NSLog(@"No data From Search");
    }
}
// NSLog(@"search array ====>%@",searchArray);
[tbleView reloadData];
}

最新更新