历史记录+模糊搜索+高亮关键词

这里写代码片此篇文章用NSUserDefaults保存历史记录,同时还简单写了一点模糊搜索和高亮搜索字的标识

首先创建一个封装的模型类

#import <Foundation/Foundation.h>

@interface HggManager : NSObject

//缓存搜索的数组
+(void)SearchText :(NSString *)seaTxt;
//清除缓存的数组
+(void)removeAllArray;
@end


#import "HggManager.h"
@implementation HggManager
//实现方法
+ (void) SearchText:(NSString *)seaTxt
{
    NSUserDefaults *userDefaules = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray *myArray = [userDefaules arrayForKey:@"myArray"];
    //判断数组是否有值,没有值就创建
    if (myArray.count > 0){

    }else{
        myArray = [NSArray array];
    }
    //不可变转为可变数组 即 NSArray --> NSMutableArray
    NSMutableArray *searchTxt = [myArray mutableCopy];
    //把数据存到可变数组中
    [searchTxt addObject:seaTxt];

    //判断之处最多有几条数据
    if (searchTxt.count > 5){
        [searchTxt removeObjectAtIndex:0];
    }
    NSMutableArray *historyArray = [NSMutableArray array];
    //去重
    for (NSString *str in searchTxt) {
        if (![historyArray containsObject:str]) {
            [historyArray addObject:str];
        }
    }
    //将上述数据全部存储到NSUserDefaults中
    [userDefaules setObject:historyArray forKey:@"myArray"];
    [userDefaules synchronize];
}

//删除历史记录
+ (void)removeAllArray{
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"myArray"];
    [userDefaults synchronize];

}
@end

然后在控制中体现

#import "ViewController.h"
#import "HggManager.h"
#import "TwoViewController.h"
#define WIDHT [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *hisTableView; //历史记录的tableView
@property (nonatomic, strong) UITableView *searchTable; //模糊搜索的tableView
@property (nonatomic, strong) UITextField *hisTextField;
@property (nonatomic, strong) NSMutableArray *hisArray; //历史记录的数组
@property (nonatomic, strong) NSArray *myArray;//搜索记录的数组
@property (nonatomic, strong) UIView *topView; //nav的View
@property (nonatomic, strong) NSMutableArray *searchArr; //模糊搜索

@end

@implementation ViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    self.hisTextField.text = nil;
    self.hisTableView.hidden = NO;
    self.searchTable.hidden = YES;
    [self readNSUserDefaults];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [[UIColor greenColor] colorWithAlphaComponent:0.3];
    self.title = @"病情诊断";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];

    self.hisArray = [[NSMutableArray alloc] init];
    self.searchArr = [[NSMutableArray alloc] init];
    //搜索框
    self.topView = [[UIView alloc] init];
    self.topView.frame = CGRectMake(10, 64 + 10, WIDHT - 20, 40);
    self.topView.backgroundColor = [UIColor whiteColor];
    self.topView.layer.cornerRadius = 3;
    [self.view addSubview:self.topView];

    //搜索的按钮
    UIButton *searchImage = [UIButton buttonWithType:(UIButtonTypeCustom)];
    searchImage.frame = CGRectMake(5, 10, 30, 20);
    [searchImage setImage:[UIImage imageNamed:@"搜索中@2x"] forState:(UIControlStateNormal)];
    [self.topView addSubview:searchImage];

    //搜索框
    self.hisTextField = [[UITextField alloc] init];
    self.hisTextField.frame = CGRectMake(searchImage.frame.size.width + 10, 10, WIDHT - 80, 20);
    self.hisTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.hisTextField.delegate = self;
    self.hisTextField.returnKeyType = UIReturnKeySearch;//更改键盘的return
    self.hisTextField.placeholder = @"请输入诊断名称";
    [self.hisTextField addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
    [self.topView addSubview:self.hisTextField];

    //创建搜索的tableView
    self.searchTable = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.frame.size.height + self.topView.frame.origin.y + 10, WIDHT, HEIGHT - (self.topView.frame.size.height + self.topView.frame.origin.y + 1)) style:UITableViewStyleGrouped];
    self.searchTable.delegate = self;
    self.searchTable.dataSource = self;
    self.searchTable.rowHeight = 130;
    self.searchTable.tableFooterView = [[UIView alloc]init];
    self.searchTable.hidden = YES;
    [self.view addSubview:self.searchTable];

    //创建历史记录的tableView
    self.hisTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,self.topView.frame.size.height + self.topView.frame.origin.y + 10 , WIDHT,HEIGHT - (self.topView.frame.size.height + self.topView.frame.origin.y + 10)) style:UITableViewStylePlain];
    self.hisTableView.delegate = self;
    self.hisTableView.dataSource = self;
    self.hisTableView.hidden = NO;
    self.hisTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview: self.hisTableView];
    // Do any additional setup after loading the view, typically from a nib.
}
//点击搜索按钮
-(BOOL)textFieldShouldReturn:(UITextField *)textField{//搜索方法

    if (textField.text.length > 0) {

        [HggManager SearchText:textField.text];//缓存搜索记录
        [self readNSUserDefaults];

    }else{
        NSLog(@"请输入查找内容");
    }
    //此处应该就是搜索的数据,这里我们作为第二页的跳转来写
    TwoViewController *twoVC = [[TwoViewController alloc] init];
    [self.navigationController pushViewController:twoVC animated:YES];
    return YES;
}
//监听文本框刚开始的变化 模糊搜索
-(void)valueChanged:(UITextField *)textField{


    if(!(textField.text.length == 0)){
        //此处为假数据
        self.searchArr =  [NSMutableArray arrayWithObjects:@"1234567",@"155555",@"09875",@"090",nil];
        NSLog(@"%@",self.searchArr);
        [self.searchTable reloadData];
        self.hisTableView.hidden = YES;
        self.searchTable.hidden = NO;
    }else{
        self.hisTableView.hidden = NO;
        self.searchTable.hidden = YES;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(tableView == self.searchTable){
        return 1;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(tableView == self.searchTable){
        return self.searchArr.count;
    }else{
        if (section==0) {
            if (_myArray.count>0) {
                return _myArray.count+1+1;
            }else{
                return 1;
            }
        }else{
            return 0;
        }
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if(tableView == self.searchTable){
        static NSString *cellIdentity = @"leftCell";
        UITableViewCell *cells = [tableView dequeueReusableCellWithIdentifier:cellIdentity];
        if (!cells) {
            cells = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
        }

        if(self.searchArr.count == 0){
            NSLog(@"预防出错");
        }else{
            cells.textLabel.text = self.searchArr[indexPath.row];
            NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:self.searchArr[indexPath.row]];
            //位置
            NSRange rang = [self.searchArr[indexPath.row] rangeOfString:self.hisTextField.text];
            //设置属性
            [attributeString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], NSForegroundColorAttributeName, nil] range:rang];
            cells.textLabel.attributedText = attributeString;
        }
        return cells;
    }else{
        if (indexPath.section==0) {
            if(indexPath.row ==0){
                UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
                cell.textLabel.text = @"历史搜索";
                cell.textLabel.textColor = [UIColor blackColor];
                return cell;
            }else if (indexPath.row == _myArray.count+1){
                UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
                cell.textLabel.text = @"清除历史记录";
                cell.textLabel.textColor = [UIColor blackColor];;
                cell.textLabel.textAlignment = NSTextAlignmentCenter;
                return cell;
            }else{
                UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
                NSArray* reversedArray = [[_myArray reverseObjectEnumerator] allObjects];
                cell.textLabel.text = reversedArray[indexPath.row-1];
                return cell;
            }
        }else{
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            return cell;
        }

    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(tableView == self.searchTable){
        return 0.1;
    }
    if (section==0) {
        return 0;
    }else{
        return 10;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.hisTableView.estimatedRowHeight = 44.0f;
    return UITableViewAutomaticDimension;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if(tableView == self.searchTable){
        self.hisTextField.text = self.searchArr[indexPath.row];
        [HggManager SearchText:self.searchArr[indexPath.row]];//缓存搜索记录
        [self readNSUserDefaults];
        //此处应该就是搜索的数据,这里我们作为第二页的跳转来写
        TwoViewController *twoVC = [[TwoViewController alloc] init];
        [self.navigationController pushViewController:twoVC animated:YES];


    }else{
        [self.hisTableView deselectRowAtIndexPath:indexPath animated:YES];
        if (indexPath.row == _myArray.count+1) {//清除所有历史记录
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除历史记录" message:@"" preferredStyle: UIAlertControllerStyleAlert];


            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [HggManager removeAllArray];
                _myArray = nil;
                [self.hisTableView reloadData];
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:deleteAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }else{
            self.hisTextField.text = self.myArray[indexPath.row ];
            //此处应该就是搜索的数据,这里我们作为第二页的跳转来写
            TwoViewController *twoVC = [[TwoViewController alloc] init];
            [self.navigationController pushViewController:twoVC animated:YES];
        }

    }
}

-(void)readNSUserDefaults{//取出缓存的数据
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray * myArray = [userDefaultes arrayForKey:@"myArray"];
    self.myArray = myArray;
    [self.hisTableView reloadData];
    NSLog(@"myArray======%@",myArray);
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.hisTextField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值