自定义textfield实现模糊搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
//添加字符串分类
@interface NSString (Pinyin)
//将汉字转为拼音
- (NSString *)transformToPinyin;
 
//获取拼音的首字母
- (NSString *)transformToPinyinFirstLetter;
 
@implementation NSString (Pinyin)
- (NSString *)transformToPinyin {
 
    NSMutableString *mutableString = [NSMutableString stringWithString:self];
 
    CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
 
    mutableString = (NSMutableString *)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
 
    mutableString = [[mutableString stringByReplacingOccurrencesOfString:@" " withString:@""]mutableCopy];
 
    return mutableString.lowercaseString.copy;
}
 
- (NSString *)transformToPinyinFirstLetter {
 
    NSMutableString *stringM = [NSMutableString string];
 
    NSString *temp = nil;
 
    for (int i = 0; i < [self length]; i++) {
 
        temp = [self substringWithRange:NSMakeRange(i, 1)];
 
        NSMutableString *mutableString = [NSMutableString stringWithString:temp];
        CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
        mutableString = (NSMutableString *)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
 
        mutableString = [[mutableString substringToIndex:1]mutableCopy];
 
        [stringM appendString:(NSString *)mutableString];
    }
    return stringM.lowercaseString.copy;
}
@end
 
//分解需要搜索的内容
 
@interface SearchModel : NSObject
 
@property (nonatomic,copy) NSString *totalName;
 
@property (nonatomic,copy) NSString *pinyin;
 
@property (nonatomic,copy) NSString *firstLetter;
 
//自定义搜索框 继承自UITextfield
@implementation Searchbar
 
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
 */// 修改文本展示区域,一般跟editingRectForBounds一起重写
- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect inset = CGRectMake(bounds.origin.x+25, bounds.origin.y, bounds.size.width-30, bounds.size.height);//更好理解些
    return inset;
}
 
// 重写来编辑区域,可以改变光标起始位置,以及光标最右到什么地方,placeHolder的位置也会改变
-(CGRect)editingRectForBounds:(CGRect)bounds
{
    CGRect inset = CGRectMake(bounds.origin.x+25, bounds.origin.y, bounds.size.width-30, bounds.size.height);//更好理解些
    return inset;
}
 
//在需要的控制器实现,分解所有数据放在sroreArray,搜索到的放在searchArray
#import "Searchbar.h"
#import "SearchModel.h"
#import "NSString+Pinyin.h"
@interface SecondControllerViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSArray *dataArray;
@property(nonatomic,strong)NSMutableArray *stroeArray;
@property(nonatomic,weak)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *searchArray;
@property(nonatomic,assign)BOOL searchState;
@end
 
@implementation SecondControllerViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
     self.navigationController.navigationBar.hidden = YES;
     Searchbar *searchTextField = [[Searchbar alloc]initWithFrame:CGRectMake(45, 30, 250 ,30)];
    [self.view addSubview:searchTextField];
    searchTextField.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    searchTextField.placeholder = @"search";
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:searchTextField.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(15, 15)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = searchTextField.bounds;
    maskLayer.path = maskPath.CGPath;
    searchTextField.layer.mask = maskLayer;
 
    UIImage *im = [UIImage imageNamed:@"btn_plus"];
    UIImageView *iv = [[UIImageView alloc] initWithImage:im];
    UIView *lv = [[UIView alloc] initWithFrame:CGRectMake(-10, 0, 50, 200)];
    iv.center = lv.center;
    [lv addSubview:iv];
    searchTextField.leftViewMode = UITextFieldViewModeAlways;
    searchTextField.leftView = lv;
 
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0,70, self.view.frame.size.width, 4)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:lineView];
 
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 74, self.view.frame.size.width, self.view.frame.size.height -74)];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    tableView.dataSource = self;
    tableView.delegate = self;
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
 
    NSArray *dateArray = @[@"但是",@"asfkjkj",@"海贼王",@"2313",@"孙悟空",@"二郎神",@"索隆",@"naturo",@"sasikai"];
    self.dataArray = dateArray;
    NSMutableArray *storeArray = [[NSMutableArray alloc]init];
    self.stroeArray = storeArray;
    NSMutableArray *searchArray = [[NSMutableArray alloc]init];
    self.searchArray = searchArray;
 
    for (int i = 0; i <dateArray.count; i++) {
        NSString *name = dateArray[i];
        NSString *pinyin = [name transformToPinyin];
        NSString *firstLetter = [name transformToPinyinFirstLetter];
 
        SearchModel *model = [[SearchModel alloc]init];
        model.totalName = name;
        model.pinyin = pinyin;
        model.firstLetter = firstLetter;
        [self.stroeArray addObject:model];
    }
 
 
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}
 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchState) {
        return self.searchArray.count;
    }
    return self.stroeArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (self.searchState) {
        SearchModel *model = self.searchArray[indexPath.row];
        cell.textLabel.text =model.totalName;
    }else{
        SearchModel *model = self.stroeArray[indexPath.row];
        cell.textLabel.text =model.totalName;
    }
 
    return cell;
}
-(void)textChanged:(NSNotification *)notification{
    UITextField *textField = (UITextField *)[notification object];
    [self startSearchWithString:textField.text];
}
-(void)startSearchWithString:(NSString *)string{
    if ([string isEqualToString:@""]) {
        self.searchState = NO;
        [self.tableView reloadData];
        return;
    }
    if (self.dataArray.count > 0) {
        //搜索之前移除数组内的所有数据,搜索后重新加载数据
        [self.searchArray removeAllObjects];
    }
 
    NSString *key = string.lowercaseString;
 
    NSMutableArray *mArray = [NSMutableArray array];
 
    /**
     *  从所有的数据里搜索相对应的字符串并将符合条件的字符串存入一个临时数组中
     */
    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {
 
        [self.stroeArray enumerateObjectsUsingBlock:^(SearchModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
 
            NSString *totalName = obj.totalName.lowercaseString;
            NSString *pinyin = obj.pinyin.lowercaseString;
            NSString *firstLetter = obj.firstLetter.lowercaseString;
 
            NSRange range = [totalName rangeOfString:key];
 
            if (range.length > 0) {
 
                [mArray addObject:obj];
            }else {
 
                if ([firstLetter containsString:key]) {
 
                    [mArray addObject:obj];
                }else {
 
                    if ([firstLetter containsString:[key substringToIndex:1]]) {
 
                        if ([pinyin containsString:key]) {
 
                            [mArray addObject:obj];
                        }
                    }
                }
            }
        }];
        //遍历临时数组,再次判断临时数组内的数据将其添加到搜索结果数据中
        [mArray enumerateObjectsUsingBlock:^(SearchModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
 
            if (![self.searchArray containsObject:obj]) {
 
                [self.searchArray addObject:obj];
            }
        }];
        self.searchState = YES;
    }
    //刷新数据
    [self.tableView reloadData];
}
@end

Add a Comment

电子邮件地址不会被公开。 必填项已用*标注