搜索 和 关键字高亮

@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;

  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值