使用动态生成的数组使用搜索栏
Posted
技术标签:
【中文标题】使用动态生成的数组使用搜索栏【英文标题】:Use Search Bar using dynamically generated array 【发布时间】:2016-12-28 05:48:21 【问题描述】:我想使用 SearchBar 在服务的帮助下动态生成元素。就像,如果我将“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];
【问题讨论】:
看看正则表达式。 根据您的代码,服务器端需要为您发送的参数做工作。前端没有工作。 在您的UIViewController
顶部实现一个搜索栏,允许用户输入他/她想要的任何内容。并根据您的要求按 search 按钮或更改字符执行搜索。将值传递给 API,然后在 UITableView
中显示响应
检查这个***.com/questions/18719517/…。在委托方法中,您可以调用具有上述代码的方法。当用户在搜索栏中写字母时,将调用该方法。试试这个并更新代码。然后我可以检查问题出在哪里,因为我还不知道您的所有要求。
@Amanpreet :) :) 您的指导。谢谢你:)
【参考方案1】:
解决办法如下:
.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 文件
#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
【讨论】:
【参考方案2】:从动态数组中搜索任何内容的简便方法
你的控制器.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];
【讨论】:
以上是关于使用动态生成的数组使用搜索栏的主要内容,如果未能解决你的问题,请参考以下文章
使用jQuery从数组数组动态生成<table>时如何排除ID列