UISearchBar
//顶部搜索栏--加到navigationItem.titleView
UISearchBar * searchbar=[[UISearchBar alloc]initWithFrame:CGRectMake(40*SCREEN_SCALEW,0, self.view.frame.size.width-40*SCREEN_SCALEW*2,44*SCREEN_SCALEH)];
searchbar.placeholder=@"搜索";
searchbar.searchBarStyle=UISearchBarStyleMinimal;
self.navigationItem.titleView =searchbar;
// 设置搜索框的圆角
UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
if (searchField) {
searchField.layer.cornerRadius = 14.0f;
[searchField setBackgroundColor:[UIColor whiteColor]];
searchField.layer.borderColor = [UIColor colorWithRed:247/255.0 green:75/255.0 blue:31/255.0 alpha:1].CGColor;
searchField.layer.borderWidth = 1;
searchField.layer.masksToBounds = YES;
// 光标的颜色
[searchField setTintColor:[UIColor redColor]];
}
UIButton *downSearchButton = [UIButton buttonWithType:UIButtonTypeCustom];
[downSearchButton setTitle:@"搜索" forState:UIControlStateNormal];
[downSearchButton setImage:[UIImage imageNamed:@"Triangle"] forState:UIControlStateNormal];
[downSearchButton addTarget:self action:@selector(tapdownSearchButton:) forControlEvents:UIControlEventTouchUpInside];
[searchField addSubview:downSearchButton];
//Autolayout
downSearchButton.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *views = NSDictionaryOfVariableBindings(downSearchButton);
//设置水平方向约束
[searchField addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[downSearchButton(21)]-|" options:NSLayoutFormatAlignAllLeading | NSLayoutFormatAlignAllLeft metrics:nil views:views]];
//设置高度约束
[searchField addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[downSearchButton(21)]" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:nil views:views]];
//设置垂直方向居中约束
[searchField addConstraint:[NSLayoutConstraint constraintWithItem:downSearchButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:searchField attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
downSearchButton.frame = CGRectMake(3, 2, searchField.frame.size.width, searchField.frame.size.height);
downSearchButton.backgroundColor = [UIColor blueColor];
实现模糊搜索
pragma mark ************* UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSMutableArray * mArr = [NSMutableArray new];
if (searchText.length>0) {
for (MediaListPlayModel *model in self.mediaListModelArr) {
NSRange titleResult=[model.content rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResult.length>0)
{
[mArr addObject:model];
}
}
_mediaListModelArr = [mArr copy];
}else{
_mediaListModelArr = _originalDatas;
}
[hospitalMedieView.mediaList reloadData];
}