搜尋控制元件
阿新 • • 發佈:2018-11-08
ViewController.m
#import “ViewController.h”
@interface ViewController ()
<UITableViewDataSource,UITableViewDelegate>
{
NSArray *allArr; // 全資料陣列
NSArray *filterArr; // 過濾後的陣列
UITableView *tbv; // 表格
UISearchDisplayController *seDC; // 搜尋控制器
}
@end
@implementation ViewController
接下來是viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
// 6.資料來源陣列 allArr = @[@"abcddde",@"abcd",@"a",@"bcde",@"aabc",@"ebd",@"abcdefg"]; // 表格 // 1.frame tbv = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain]; // 2.設定資料來源和代理 tbv.dataSource = self; tbv.delegate = self; // 3.把表格新增到主檢視 [self.view addSubview:tbv]; // 搜尋條 UISearchBar *seBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)]; seBar.placeholder = @"請輸入想搜尋的內容!!"; // 將搜尋條設定成表格的組頭檢視 tbv.tableHeaderView = seBar; // 初始化搜尋控制器 seDC = [[UISearchDisplayController alloc]initWithSearchBar:seBar contentsController:self]; // 設定新的控制器的代理 和資料來源 seDC.searchResultsDelegate = self; seDC.searchResultsDataSource = self; } // 實現協議中的方法 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ if(tableView == tbv){ return allArr.count; }else{ // 謂詞 ->過濾 // 建立謂詞 - >根據我們搜尋的內容的變化而變化 NSPredicate *pred = [NSPredicate predicateWithFormat:@"self contains [cd] %@",seDC.searchBar.text]; // 通過謂詞去過濾 陣列(allArr) filterArr = [NSArray arrayWithArray:[allArr filteredArrayUsingPredicate:pred]]; return filterArr.count; } } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *reuse = @"cell"; // 先用舊的 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse]; // 再用新的 if(!cell){ cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse]; } if(tableView == tbv){ // 展示資料. cell.textLabel.text = allArr[indexPath.row]; }else{ // 過濾之後的世界了. cell.textLabel.text = filterArr[indexPath.row]; } return cell; } // 隱藏狀態列 -(BOOL)prefersStatusBarHidden{ return YES; }
@end
效果執行圖: