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

标签 ios objective-c xcode uisearchbar

我想使用 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];
}

最佳答案

解决方法如下:

.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

关于ios - 使用动态生成的数组来使用搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41356079/

相关文章:

ios - 应用程序崩溃并出现错误 : -[NSNull length]: unrecognized selector sent to instance

iOS7 Xcode 5 升级导致长按崩溃应用程序

objective-c - 如何调用 UItableview 委托(delegate)方法。 tableview什么时候在 "for"循环?

objective-c - 首先 seekToTime,然后用 setVolumeRampFromStartVolume 淡入

ios - 在 Objective-C 中将值从一个 ViewController 传递到另一个

iphone - iOS 界面方向

ios - 如何更改导航栏标题的颜色?

ios - Swift 属性观察者和 nil

iphone - 所有单元格的UITableViewCell BackgroundImage

iphone - 如何从 UIImage 获取透明区域?