UITableView继承UIScrollView,所以拥有UIScrollView的所有属性.在iOS开发中,UITableView的应用十分广泛和普遍,例如:大部分应用程序中的搜索栏,其搜索结果就可以是一个UITableView.基于此,做了一个关于搜索的小Demo 以供参考.
< Demo 如下 >:
ViewController.m 文件:
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
UITextField *textField;
}
@property (weak, nonatomic) IBOutlet UITableView *tbView;
@property (strong, nonatomic) NSArray *dataArr; //筛选过后的数据源
@property (strong, nonatomic) NSMutableArray *mdataArr;
@end
@implementation ViewController
- (void)dealloc {
//移除通知监听者
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.mdataArr = [NSMutableArray array];
self.tbView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
// 系统字体作为数据源
self.mdataArr = (NSMutableArray *)[UIFont familyNames];
self.dataArr = self.mdataArr;
//自定义导航栏
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 44)];
view.backgroundColor = [UIColor blueColor];
[self.view addSubview:view];
//textFile
textField = [[UITextField alloc] initWithFrame:CGRectMake(40, 10, 300, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.backgroundColor = [UIColor whiteColor];
textField.keyboardType = UIKeyboardTypeDefault;
[view addSubview:textField];
[self.mdataArr addObject:textField.text];
//监听TextFieldText内容的改变
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:nil];
}
//通知
- (void)textChange:(NSNotification *)notification
{
NSString *text = textField.text;
if ([text length] == 0) {
self.dataArr = self.mdataArr;
[self.tbView reloadData];
return;
}
//过滤条件
NSString *p = [NSString stringWithFormat:@"SELF LIKE[c] '*%@*'", text];
//使用谓词过滤
NSPredicate *predicate = [NSPredicate predicateWithFormat:p];
self.dataArr = [self.mdataArr filteredArrayUsingPredicate:predicate];
[self.tbView reloadData];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"can";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
cell.textLabel.text = self.dataArr[indexPath.row];
cell.textLabel.font = [UIFont fontWithName:self.dataArr[indexPath.row] size:17];
return cell;
}
@end