UISearchBar實(shí)現(xiàn)本頁面搜索跳轉(zhuǎn)功能,這個(gè)效果是iOS8.0之前的主流的效果
一、先看個(gè)效果

2016-07-12_14-37-01.gif
二、思路分析和代碼實(shí)現(xiàn)
這個(gè)效果的實(shí)現(xiàn),我覺的主要有二個(gè)難點(diǎn)(1.從大量的數(shù)據(jù)源中匹配到符合要求的;2.源頁面和搜索到的頁面的點(diǎn)擊事件)。
2-1.解決第一個(gè)問題(從大量的數(shù)據(jù)源中匹配到符合要求)
注意了,開始上代碼了
#pragma mark UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSString* str = searchText;
//這一句代碼的妙處在于:可以用self.string的length來進(jìn)行判斷是原數(shù)據(jù)還是搜索的數(shù)據(jù)
self.string = str;
NSLog(@"%@",str);
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c]%@ ",str];
//清空搜索數(shù)組
[self.resultArray removeAllObjects];
self.resultArray = [NSMutableArray arrayWithArray:[_dataArray filteredArrayUsingPredicate:namePredicate]];
[self.collectionView reloadData];
}
2-2.源頁面和搜索到的頁面的點(diǎn)擊事件
需要注意的是:DataSource和點(diǎn)擊事件的delegate二個(gè)部分都可以通過self.string來進(jìn)行判斷。
#pragma mark--UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
if (self.string.length == 0) {
return _dataArray.count;
}else{
return self.resultArray.count;
}
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
InvestmentsViewCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
if (self.string.length == 0) {
cell.lable.text = _dataArray[indexPath.item];
NSLog(@"%@",cell);
}else{
cell.lable.text = self.resultArray[indexPath.item];
NSLog(@"%@",cell);
}
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"%ld %ld",indexPath.section,indexPath.item);
testController *test = [[testController alloc] init];
if (self.string.length == 0) {
test.str = _dataArray[indexPath.item];
}else{
test.str = self.resultArray[indexPath.item];
}
[self.navigationController pushViewController:test animated:YES];
}
三.結(jié)束
以上的效果的實(shí)現(xiàn),代碼已經(jīng)實(shí)現(xiàn)。之前本人用UISearchController實(shí)現(xiàn)了另外一種的本頁面的實(shí)現(xiàn)的效果,參考那篇文章看,歡迎各位同仁
批評指正,共同進(jìn)步。有什么問題可以通過QQ聯(lián)系1312940166。