iOS UISearchBar使用

释放双眼,带上耳机,听听看~!

上一篇简述了UISearchBar的属性及方法,本篇简单练习使用。

具体属性及方法可以参考上一篇UISearchBar简介:UISearchBar简介

首先看一下效果图:

下面贴上代码:

#import "ViewController.h"
@interface ViewController ()<UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSArray *array;
@property (nonatomic, strong) NSArray *searchArray;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tabelView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
_array = @[@"mac", @"kobe", @"tracy", @"allen", @"ios", @"android", @"swift", @"object", @"activity"];
_searchArray = [_array copy];
[self creatControl];
}
- (void)creatControl
{
_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(100, 100, 200, 44)];
_searchBar.barTintColor = [UIColor whiteColor];
_searchBar.delegate = self;
[self.view addSubview:_searchBar];
_tabelView = [[UITableView alloc] initWithFrame:CGRectMake(100, 144, 200, 300)];
_tabelView.backgroundColor = [UIColor whiteColor];
_tabelView.delegate = self;
_tabelView.dataSource = self;
[self.view addSubview:_tabelView];
}
#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchText];
_searchArray = [[_array filteredArrayUsingPredicate:predicate] copy];
}else {
_searchArray = [_array copy];
}
[_tabelView reloadData];
}
#pragma mark - UITabelViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _searchArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *searchCell = @"searchCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:searchCell];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:searchCell];
}
cell.textLabel.text = _searchArray[indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"点击了%@", _searchArray[indexPath.row]);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[_searchBar resignFirstResponder];
}
@end

实际开发中,数组保存的多为模型,搜索过滤时可以用下面方法:(其中name为模型里的变量)

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@", searchText];
_searchArray = [[_array filteredArrayUsingPredicate:predicate] copy];
}else {
_searchArray = [_array copy];
}
[_tableView reloadData];
}

 

人已赞赏
iOS文章

iOS UISearchBar简介

2020-2-24 2:53:59

iOS文章

iOS Extension Category Protrol 理解

2020-2-24 4:57:56

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索