設置帶有導航欄的根視圖控制器
RootViewController.h
@interface RootViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
UITableView *_tableView;
}
@property(nonatomic, retain)NSArray *data; //存放原本的數據
@property(nonatomic, retain)NSArray *filterData; //用於存放刪選後的數據
- (void)viewDidLoad
{
[super viewDidLoad];
//創建輸入框
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
textField.delegate = self;
textField.borderStyle = UITextBorderStyleRoundedRect;
//關閉大寫
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
self.navigationItem.titleView = textField;
[textField release];
//創建表視圖
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];
//取得數據
/*
[@"1",@"2"]
*/
_data = [[UIFont familyNames] retain];
_filterData = [_data retain];
//註冊一個通知
//輸入框裏面的內容發生改變的時候發送通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAction:) name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)changeAction:(NSNotification *)notificiation {
//輸入框輸入的內容
NSLog(@"%@",notificiation.object);
UITextField *textField = notificiation.object;
//定義謂詞
//[c]標示不區分大小寫
NSString *t = [NSString stringWithFormat:@"self like [c]'*%@*'",textField.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:t];
//過濾元素
self.filterData = [_data filteredArrayUsingPredicate:predicate];
//刷新視圖
[_tableView reloadData];
}
#pragma mark - UITableView dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _filterData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *iden = @"cell110";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden] autorelease];
}
cell.textLabel.text = _filterData[indexPath.row];
return cell;
}
#pragma mark - UITextField delegate
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//
// /*
// textField.text裏面存放是用戶以前輸入的內容
// string:標示用戶剛剛輸入的字符
// */
//
// NSLog(@"textField:%@",textField.text);
// NSLog(@"string:%@",string);
//
// //輸入框輸入的內容
// NSString *text = [NSString stringWithFormat:@"%@%@",textField.text,string];
//
// //定義謂詞
// //[c]標示不區分大小寫
// NSString *t = [NSString stringWithFormat:@"self like [c]'*%@*'",text];
// NSPredicate *predicate = [NSPredicate predicateWithFormat:t];
//
// //過濾元素
// self.filterData = [_data filteredArrayUsingPredicate:predicate];
//
// //刷新視圖
// [_tableView reloadData];
//
//
// return YES;
//}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
//收起鍵盤
[textField resignFirstResponder];
return YES;
}