iOS开发总结-搜索功能实现--使用SKTag

TagsTableViewController.h 文件

#import <UIKit/UIKit.h>
#import "personSearch.h"

@interface TagsTableViewController : UITableViewController<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,retain) personSearch *searchBar;

@property (nonatomic, strong) NSString *key;


@end

TagsTableViewController.m 文件

#import "TagsTableViewController.h"
#import "TagsTableCell.h"
#import "SKTagView.h"
#import "SKTagButton.h"
#import "FTMacro.h"
#import "SearchResultViewController.h"
#import "DBStrore.h"
#import "Utilities.h"
//#import "guideInfoViewController.h"
//#import "reviewInfoViewController.h"
//#import "mShopInfoViewController.h"
//#import "tempModel.h"
#import "BaseSVRRequestOperator.h"
//#import "pointRuleViewController.h"
//#import "ALBBTradeObject.h"
#import "HttpConnect.h"
#import "PicViewController.h"

#define SCREEN_WIDTH    ([UIScreen mainScreen].bounds.size.width)
//Cell
static NSString *const kTagsTableCellReuseIdentifier = @"TagsTableCell";


@interface UIImage (SKTagView)
+ (UIImage *)imageWithColor:(UIColor *)color;
@end

@interface TagsTableViewController ()<UISearchBarDelegate,SearchResultViewControllerDelegate>

@property (nonatomic, strong) SearchResultViewController *searchResultView;
@property (nonatomic, strong) NSMutableArray *hotKeyArray;
@property (nonatomic, strong) NSMutableArray *historySearchArray;

@property (nonatomic, strong) NSMutableArray *guideArray;
@property (nonatomic, strong) NSMutableArray *shopArray;

@property (nonatomic, strong) BaseSVRRequestOperator *netWorking;
@property (strong, nonatomic)  UIButton *mLookPicButton;
@end

@implementation TagsTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"TagsTableViewController viewDidLoad ...");
    self.view.backgroundColor =[UIColor colorWithRed:1.00 green:1.00 blue:1.00 alpha:1.00];
    self.hotKeyArray = [[NSMutableArray alloc] init];
    
    self.netWorking = [BaseSVRRequestOperator new];
    self.guideArray = [NSMutableArray new];
    self.shopArray = [NSMutableArray new];
    
    [self initLeftBarButtonItem];
    /*
    [self initRightBarButtonItem000];
    [self searchBarInit000];
     */
    [self initRightBarButtonItem];
    [self searchBarInit];
    
    [self setHeadView];
    
   
    if([DBStrore sharedDBStore].HistorySearchArray.count > 0)
    {
        self.historySearchArray = [[NSMutableArray alloc] initWithArray:[DBStrore sharedDBStore].HistorySearchArray];
    }
    else
    {
        self.historySearchArray = [NSMutableArray new];
    }
    
    if([DBStrore sharedDBStore].hotKeyArray.count > 0)
    {
        self.hotKeyArray = [DBStrore sharedDBStore].hotKeyArray;
    }
    else
    {
        [self getHotSearchKeyword];
        
    }
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideBarSearch:) name:@"hideBarSearch" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(freshCapPicCount:) name:@"freshCapPicCount" object:nil];
}

- (void)hideBarSearch:(id)notification
{
    [self.searchBar resignFirstResponder];
}

- (void)setHeadView
{
}

- (void)detailBtn
{
    [self.searchBar resignFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = NO;
    //开启定时器
    // [scrollView.myTimer setFireDate:[NSDate distantPast]];
    NSLog(@"search viewWillAppear:%d",[DBStrore sharedDBStore].CapPicArray.count);
    [_mLookPicButton setTitle:[NSString stringWithFormat:@"对比(%d)",[DBStrore sharedDBStore].CapPicArray.count] forState: UIControlStateNormal];
}

- (void)lookPicBtnClick
{
    PicViewController *picVC = (PicViewController *)[[UIStoryboard storyboardWithName:@"picview" bundle:nil] instantiateViewControllerWithIdentifier:@"PicViewController"];
    
    [self.navigationController pushViewController:picVC animated:YES];
    
}

-(void) freshCapPicCount:(NSNotification*)notify
{
    NSLog(@"search view freshCapPicCount:%d",[DBStrore sharedDBStore].CapPicArray.count);
    [_mLookPicButton setTitle:[NSString stringWithFormat:@"对比(%d)",[DBStrore sharedDBStore].CapPicArray.count] forState: UIControlStateNormal];
}

//导航栏左边按钮
- (void)initLeftBarButtonItem
{
    NSLog(@"返回");
    
    UIButton *backimgbtn = [[UIButton alloc] initWithFrame:CGRectMake(0,0,30,30)];
    [backimgbtn setImage:[UIImage imageNamed:@"back_b.png"]forState:UIControlStateNormal];
    [backimgbtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [backimgbtn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    backimgbtn.backgroundColor = [UIColor clearColor];
    [backimgbtn setTitleColor:[UIColor redColor]forState:UIControlStateNormal];
    backimgbtn.titleLabel.font = [UIFont systemFontOfSize: 15.0];
    [backimgbtn addTarget:self action:@selector(cancelNav) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *leftButton =  [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setTitle:@"返回" forState:UIControlStateNormal];
    [leftButton setTitle:@"返回" forState:UIControlStateHighlighted];
    [leftButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [leftButton setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    [leftButton setTitleColor:self.view.tintColor forState:UIControlStateNormal];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [leftButton addTarget:self action:@selector(cancelNav) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setFrame:CGRectMake(18,0,40,30)];
   
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    
    [leftView addSubview:backimgbtn];
    [leftView addSubview:leftButton];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
    
    
    
    
    
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        UIBarButtonItem *negativeSeperator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        negativeSeperator.width = -12;
        [self.navigationItem setLeftBarButtonItems:@[negativeSeperator, leftBarButtonItem]];
    }
    else
    {
        [self.navigationItem setLeftBarButtonItem:leftBarButtonItem animated:NO];
    }
    
    
   
}
//导航栏右边按钮
- (void)initRightBarButtonItem
{
    NSLog(@"对比");
    UIButton *rightButton =  [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"对比(..)" forState:UIControlStateNormal];
    [rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [rightButton setTitleColor:self.view.tintColor forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(lookPicBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setFrame:CGRectMake(0, 0, 75, 22)];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        UIBarButtonItem *negativeSeperator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        negativeSeperator.width = -12;
        [self.navigationItem setRightBarButtonItems:@[negativeSeperator, rightBarButtonItem]];
    }
    else
    {
        [self.navigationItem setRightBarButtonItem:rightBarButtonItem animated:NO];
    }
     _mLookPicButton=rightButton;
    
    /*
     [self.navigationItem setLeftBarButtonItem:nil];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setFrame:CGRectMake(0, 0, 0, 0)];
//    [leftButton setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [self.navigationItem setLeftBarButtonItem:leftBarButtonItem];
    */
}

//初始化搜索栏
- (void)searchBarInit {
    
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(60, 0, kScreenWidth - 148, 44)];
    searchView.backgroundColor = [UIColor clearColor];
    
    self.searchBar = [[personSearch alloc] initWithFrame:CGRectMake(0, 0, searchView.frame.size.width, searchView.frame.size.height)];
    self.searchBar.backgroundColor = [UIColor clearColor];
    self.searchBar.showsScopeBar = NO;
    if(IsiOS8Later)
    {
        self.searchBar.returnKeyType = UIReturnKeySearch;
    }
    self.searchBar.delegate = self;
    [self.searchBar becomeFirstResponder];
    [searchView addSubview:self.searchBar];
    
    self.navigationItem.titleView = searchView;
    
}




- (void)cancelNav{
    [self.searchBar resignFirstResponder];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)cleanHis:(id)sender{
   
    [self.historySearchArray removeAllObjects];
    [[DBStrore sharedDBStore].HistorySearchSet removeAllObjects];
    [[DBStrore sharedDBStore].HistorySearchArray removeAllObjects];
    [self.tableView reloadData];
    
    [self saveSearchHistory];
  
}
- (void)getHotSearchKeyword
{
    HttpConnect * connect = [[HttpConnect alloc] init];
    connect.delegate = self;
//    NSNumber *lastid = [NSNumber numberWithInt:self.last_id];
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
//    [dic setObject:lastid forKey:@"lastid"];
    
    
    [connect postRequestForPostValue:dic url:@"gethotkey.php" requestTag:1];
    
}
-(void)postRequestStarted:(AFHTTPRequestOperation*)request manage:(AFHTTPRequestOperationManager*)manage{
    
    NSLog(@"REQ START");
}
// 从服务器取热门搜索关键字的回调
-(void)postRequestFinished:(AFHTTPRequestOperation*)request manage:(AFHTTPRequestOperationManager*)manage{ NSLog(@"REQ FINISHED"); NSDictionary * dictionary = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableLeaves error:nil ]; NSString * status = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"status"]]; // NSLog(@"status=%@",status); if([status isEqualToString: @"0"]){ NSArray *dataArray = [request.responseObject objectForKey:@"data"]; NSLog(@"count=%d",dataArray.count); if(dataArray) { for(int i=0;i<dataArray.count;i++) { [self.hotKeyArray addObject:[dataArray objectAtIndex:i]]; } } [self.tableView reloadData]; [DBStrore sharedDBStore].hotKeyArray = self.hotKeyArray; } } -(void)postRequestFailed:(AFHTTPRequestOperation*)request manage:(AFHTTPRequestOperationManager*)manage{ NSLog(@"REQ FAILED"); // [self.view addSubview:[CustomAlertView alertWith:@"0" message:NSLocalizedString(@"error", @"错误")]]; } #pragma mark - UISearchBar delegate - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { NSLog(@"searchBarTextDidBeginEditing"); [self.searchBar becomeFirstResponder]; } - (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar { NSLog(@"searchBarTextDidEndEditing"); [self.searchBar resignFirstResponder]; } - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { NSLog(@"searchBarSearchButtonClicked"); [self.searchBar resignFirstResponder]; [self starSearch:self.searchBar.text]; } // - (void)starSearch:(NSString *)key { if(key.length > 10) { key = [NSString stringWithFormat:@"%@...",[key substringToIndex:7]]; } if (![[DBStrore sharedDBStore].HistorySearchSet containsObject:key]) { if([DBStrore sharedDBStore].HistorySearchArray.count == 10) { NSString *name = [DBStrore sharedDBStore].HistorySearchArray[9]; [[DBStrore sharedDBStore].HistorySearchSet removeObject:name]; [[DBStrore sharedDBStore].HistorySearchArray removeObjectAtIndex:9]; [self.historySearchArray removeObjectAtIndex:9]; } [[DBStrore sharedDBStore].HistorySearchSet addObject:key]; [[DBStrore sharedDBStore].HistorySearchArray insertObject:key atIndex:0]; [self.historySearchArray insertObject:key atIndex:0]; [self saveSearchHistory]; [self.tableView reloadData]; } [self getSearchMessage:key]; } - (void)saveSearchHistory { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSData *bindUserLocalSettingDictionaryData = [NSKeyedArchiver archivedDataWithRootObject:[DBStrore sharedDBStore].HistorySearchArray]; [defaults setObject:bindUserLocalSettingDictionaryData forKey:FTsearchHistory]; [defaults synchronize]; } - (void)getSearchMessage:(NSString *)keyName { [DBStrore sharedDBStore].searchKey = keyName; [self.hotKeyArray removeAllObjects]; self.tableView.tableHeaderView = nil; [self.tableView reloadData]; if(!self.searchResultView) { self.searchResultView = [[SearchResultViewController alloc] initWithNibName:@"SearchResultViewController" bundle:nil]; self.searchResultView.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64); self.searchResultView.delegate = self; [self.view addSubview:self.searchResultView.view]; } [self.searchResultView getSearchListByKey:keyName]; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [self.searchBar resignFirstResponder]; } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ if(self.hotKeyArray.count > 0) { return 2; } else { return 0; } } - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)]; view.backgroundColor = [UIColor clearColor]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-12, 50)]; label.textColor = [UIColor colorWithRed:0.77 green:0.77 blue:0.78 alpha:1.00]; if (section == 1) { if(self.historySearchArray.count > 0) { label.text = @"历史搜索"; } }else{ if(self.hotKeyArray.count > 0) { label.text = @"热门搜索"; } } [view addSubview:label]; return view; } - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{ UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)]; view.backgroundColor = [UIColor clearColor]; if (section == 0) { return view; } if(self.historySearchArray.count > 0) { UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(12, 0, 130, 40)]; button.layer.cornerRadius = 5; button.layer.borderWidth = 0.5; button.layer.borderColor = [UIColor lightGrayColor].CGColor; [button setTitleColor:[UIColor colorWithRed:0.98 green:0.32 blue:0.32 alpha:1.00] forState:UIControlStateNormal]; [button setTitle:@"清除历史记录" forState:UIControlStateNormal]; [button addTarget:self action:@selector(cleanHis:) forControlEvents:UIControlEventTouchUpInside]; [button.titleLabel setFont:[UIFont systemFontOfSize:14]]; [button setBackgroundColor:[UIColor whiteColor]]; [button setImage:[UIImage imageNamed:@"clear"] forState:UIControlStateNormal]; [view addSubview:button]; } return view; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ return 40; } - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{ if(section == 0){ return 5; } return 60; } - (void)configureCell:(TagsTableCell *)cell atIndexPath:(NSIndexPath *)indexPath { cell.tagView.preferredMaxLayoutWidth = SCREEN_WIDTH; cell.tagView.padding = UIEdgeInsetsMake(12, 12, 12, 12); cell.tagView.insets = 10; cell.tagView.lineSpace = 10; [cell.tagView removeAllTags]; NSArray *array = nil; if(indexPath.section == 1){ array = self.historySearchArray; } else { array = self.hotKeyArray; } //Add Tags [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { SKTag *tag = [SKTag tagWithText:obj]; tag.textColor = [UIColor blackColor]; tag.fontSize = 14; tag.padding = UIEdgeInsetsMake(6, 15, 6, 15); tag.bgImg = [UIImage imageWithColor:[UIColor clearColor]]; tag.cornerRadius = 5; tag.borderColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.00]; tag.borderWidth = 1; tag.tag = idx; [cell.tagView addTag:tag]; }]; cell.tagView.backgroundColor = [UIColor clearColor]; cell.backgroundColor = [UIColor clearColor]; cell.tagView.tag = indexPath.section; __weak TagsTableViewController *weakSelf = self; cell.tagView.didClickTagAtIndex = ^(NSUInteger index,NSUInteger tag){ [weakSelf handleBtn:tag index:index]; }; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { TagsTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kTagsTableCellReuseIdentifier forIndexPath:indexPath]; [self configureCell:cell atIndexPath:indexPath]; return cell; } #pragma mark - Table view delegate - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { TagsTableCell *cell = nil; if (!cell) { cell = [tableView dequeueReusableCellWithIdentifier:kTagsTableCellReuseIdentifier]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } [self configureCell:cell atIndexPath:indexPath]; return [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + 1; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; } #pragma mark - User interactions //写点击事件。。。 - (void)handleBtn:(NSUInteger)section index:(NSUInteger)index { NSString *searchName = nil; if(section == 0) { searchName = self.hotKeyArray[index]; } else { searchName = self.historySearchArray[index]; } self.searchBar.text = searchName; [self.searchBar resignFirstResponder]; [self starSearch:searchName]; } @end @implementation UIImage (SKTagView) + (UIImage *)imageWithColor:(UIColor *)color { CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } @end

 

加扣群385378208即可下载工程源码,先看群信息

posted @ 2016-12-05 16:41  martin_shi  阅读(830)  评论(2)    收藏  举报