@interface SHSeachViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)NSMutableArray *listArr;
@property(nonatomic, retain)UISearchBar *searchBar;
@end
- (void)viewDidLoad {
[self createSearchBar];
}
- (void)createSearchBar {
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 260, 40);
self.navigationItem.titleView = self.searchBar;
self.searchBar.delegate = self;
self.searchBar.placeholder = @"搜索";
self.searchBar.barStyle = UIBarMetricsCompact;
self.seachBar.translucent = YES;
self.seachBar.showsSearchResultsButton = YES;
self.searchBar.searchTextPositionAdjustment = UIOffsetMake(30, 0);
[_searchBar release];
}
#pragma mark --searchBar协议方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// 把搜索栏中的汉字转化为字母或数字
NSString *searchStr = [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *strUrl = [NSString stringWithFormat@"http://........%@...", searchStr];
[self createDataWithUrl:strUrl];
}
- (void)createDataWithUrl:(NSString *)strUrl {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:strUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dic = responseObject;
self.listArr = [SHModel baseModelByArr:dic[@"result"][@"list"]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
}
- (UITableViewCell *)tableView:(UItableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *reuse = @"reuse";
SHSearchTableCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
if (!cell) {
cell = [[[SHSearchTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
}
SHModel *model = self.listArr[indexPath.row];
// 关键字高亮
NSString *keyword = self.searchBar.text;
// 清除空格
keyword = [keyword stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// 设置标签文字
NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:model.name];
// 获取标红的位置和长度
NSRange range = [model.name rangeOfString:keyword];
// 设置标签文字的属性
[attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:20]} range:range];
cell.titleLabel.text = model.name;
// 显示在titleLabel上
cell.titleLabel上
cell.titleLabel.attributedText = attrituteString;
return cell;
}
搜索 和 关键字高亮
最新推荐文章于 2020-07-05 10:10:18 发布