杨锴
2025-04-16 09a372bc45fde16fd42257ab6f78b8deeecf720b
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/**
 * Tencent is pleased to support the open source community by making QMUI_iOS available.
 * Copyright (C) 2016-2021 THL A29 Limited, a Tencent company. All rights reserved.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/MIT
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 */
 
//
//  QMUISearchController.m
//  Test
//
//  Created by QMUI Team on 16/5/25.
//
 
#import "QMUISearchController.h"
#import "QMUICore.h"
#import "QMUISearchBar.h"
#import "QMUICommonTableViewController.h"
#import "QMUIEmptyView.h"
#import "UISearchBar+QMUI.h"
#import "UITableView+QMUI.h"
#import "NSString+QMUI.h"
#import "NSObject+QMUI.h"
#import "UIView+QMUI.h"
#import "UIViewController+QMUI.h"
 
BeginIgnoreDeprecatedWarning
 
@class QMUISearchResultsTableViewController;
 
@protocol QMUISearchResultsTableViewControllerDelegate <NSObject>
 
- (void)didLoadTableViewInSearchResultsTableViewController:(QMUISearchResultsTableViewController *)viewController;
@end
 
@interface QMUISearchResultsTableViewController : QMUICommonTableViewController
 
@property(nonatomic,weak) id<QMUISearchResultsTableViewControllerDelegate> delegate;
@end
 
@implementation QMUISearchResultsTableViewController
 
- (void)initTableView {
    [super initTableView];
    
    // UISearchController.searchBar 作为 UITableView.tableHeaderView 时,进入搜索状态,搜索结果列表顶部有一大片空白
    // 不要让系统自适应了,否则在搜索结果(navigationBar 隐藏)push 进入下一级界面(navigationBar 显示)过程中系统自动调整的 contentInset 会跳来跳去
    // https://github.com/Tencent/QMUI_iOS/issues/1473
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    if ([self.delegate respondsToSelector:@selector(didLoadTableViewInSearchResultsTableViewController:)]) {
        [self.delegate didLoadTableViewInSearchResultsTableViewController:self];
    }
}
 
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if ([self.delegate isKindOfClass:QMUISearchController.class]) {
        QMUISearchController *searchController = (QMUISearchController *)self.delegate;
        if (searchController.emptyViewShowing) {
            [searchController layoutEmptyView];
        }
    }
}
 
@end
 
@interface QMUICustomSearchController : UISearchController
 
@property(nonatomic, strong) UIView *customDimmingView;
@property(nonatomic, strong) UIColor *dimmingColor;
@end
 
@implementation QMUICustomSearchController
 
- (instancetype)initWithSearchResultsController:(UIViewController *)searchResultsController {
    if (self = [super initWithSearchResultsController:searchResultsController]) {
        if (@available(iOS 15.0, *)) {
            self.dimsBackgroundDuringPresentation = YES;// iOS 15 开始该默认值为 NO 了,为了保持与旧版本一致的表现,这里改默认值
        }
    }
    return self;
}
 
- (void)setCustomDimmingView:(UIView *)customDimmingView {
    if (_customDimmingView != customDimmingView) {
        [_customDimmingView removeFromSuperview];
    }
    _customDimmingView = customDimmingView;
    
    self.dimsBackgroundDuringPresentation = !_customDimmingView;
    if ([self isViewLoaded]) {
        [self addCustomDimmingView];
    }
}
 
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self addCustomDimmingView];
}
 
- (void)addCustomDimmingView {
    UIView *superviewOfDimmingView = self.searchResultsController.view.superview;
    if (self.customDimmingView && self.customDimmingView.superview != superviewOfDimmingView) {
        [superviewOfDimmingView insertSubview:self.customDimmingView atIndex:0];
        [self layoutCustomDimmingView];
    }
}
 
- (void)layoutCustomDimmingView {
    UIView *searchBarContainerView = nil;
    for (UIView *subview in self.view.subviews) {
        if ([NSStringFromClass(subview.class) isEqualToString:@"_UISearchBarContainerView"]) {
            searchBarContainerView = subview;
            break;
        }
    }
    
    self.customDimmingView.frame = CGRectInsetEdges(self.customDimmingView.superview.bounds, UIEdgeInsetsMake(searchBarContainerView ? CGRectGetMaxY(searchBarContainerView.frame) : 0, 0, 0, 0));
}
 
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (self.customDimmingView) {
        [UIView animateWithDuration:[CATransaction animationDuration] animations:^{
            [self layoutCustomDimmingView];
        }];
    }
}
 
@end
 
@interface QMUISearchController () <QMUISearchResultsTableViewControllerDelegate>
 
@property(nonatomic,strong) QMUICustomSearchController *searchController;
@end
 
@implementation QMUISearchController
 
- (instancetype)initWithContentsViewController:(UIViewController *)viewController resultsTableViewStyle:(UITableViewStyle)resultsTableViewStyle {
    if (self = [self initWithNibName:nil bundle:nil]) {
        // 将 definesPresentationContext 置为 YES 有两个作用:
        // 1、保证从搜索结果界面进入子界面后,顶部的searchBar不会依然停留在navigationBar上
        // 2、使搜索结果界面的tableView的contentInset.top正确适配searchBar
        viewController.definesPresentationContext = YES;
        
        QMUISearchResultsTableViewController *searchResultsViewController = [[QMUISearchResultsTableViewController alloc] initWithStyle:resultsTableViewStyle];
        searchResultsViewController.delegate = self;
        self.searchController = [[QMUICustomSearchController alloc] initWithSearchResultsController:searchResultsViewController];
        self.searchController.searchResultsUpdater = self;
        self.searchController.delegate = self;
        _searchBar = self.searchController.searchBar;
        if (CGRectIsEmpty(self.searchBar.frame)) {
            // iOS8 下 searchBar.frame 默认是 CGRectZero,不 sizeToFit 就看不到了
            [self.searchBar sizeToFit];
        }
        [self.searchBar qmui_styledAsQMUISearchBar];
        
        self.hidesNavigationBarDuringPresentation = YES;
    }
    return self;
}
 
- (instancetype)initWithContentsViewController:(UIViewController *)viewController {
    return [self initWithContentsViewController:viewController resultsTableViewStyle:UITableViewStylePlain];
}
 
- (void)viewDidLoad {
    [super viewDidLoad];
    // 主动触发 loadView,如果不这么做,那么有可能直到 QMUISearchController 被销毁,这期间 self.searchController 都没有被触发 loadView,然后在 dealloc 时就会报错,提示尝试在释放 self.searchController 时触发了 self.searchController 的 loadView
    [self.searchController loadViewIfNeeded];
}
 
- (void)setSearchResultsDelegate:(id<QMUISearchControllerDelegate>)searchResultsDelegate {
    _searchResultsDelegate = searchResultsDelegate;
    self.tableView.dataSource = _searchResultsDelegate;
    self.tableView.delegate = _searchResultsDelegate;
}
 
- (void)setDimmingColor:(UIColor *)dimmingColor {
    _dimmingColor = dimmingColor;
    self.searchController.dimmingColor = dimmingColor;
    [QMUIHelper executeBlock:^{
        // - [UIDimmingView updateBackgroundColor]
        OverrideImplementation(NSClassFromString([NSString qmui_stringByConcat:@"UI", @"Dimming", @"View", nil]), NSSelectorFromString([NSString qmui_stringByConcat:@"update", @"Background", @"Color", nil]), ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) {
            return ^(UIView *selfObject) {
                
                for (UIView *subview in selfObject.superview.subviews) {
                    if ([NSStringFromClass(subview.class) isEqualToString:[NSString qmui_stringByConcat:@"_", @"UISearchController", @"View", nil]]) {
                        UISearchController *searchController = subview.qmui_viewController;
                        if ([searchController isKindOfClass:UISearchController.class]) {
                            if ([searchController respondsToSelector:@selector(dimmingColor)]) {
                                BeginIgnorePerformSelectorLeaksWarning
                                UIColor *color = [searchController performSelector:@selector(dimmingColor)];
                                EndIgnorePerformSelectorLeaksWarning
                                if (color) {
                                    [selfObject qmui_performSelector:@selector(setDimmingColor:) withArguments:&color, nil];
                                }
                            }
                        }
                        
                        break;
                    }
                }
                
                // call super
                void (*originSelectorIMP)(id, SEL);
                originSelectorIMP = (void (*)(id, SEL))originalIMPProvider();
                originSelectorIMP(selfObject, originCMD);
            };
        });
    } oncePerIdentifier:@"QMUISearchController dimmingColor"];
}
 
- (BOOL)isActive {
    return self.searchController.active;
}
 
- (void)setActive:(BOOL)active {
    [self setActive:active animated:NO];
}
 
- (void)setActive:(BOOL)active animated:(BOOL)animated {
    self.searchController.active = active;
}
 
- (UITableView *)tableView {
    return ((QMUICommonTableViewController *)self.searchController.searchResultsController).tableView;
}
 
- (void)setLaunchView:(UIView *)dimmingView {
    _launchView = dimmingView;
    self.searchController.customDimmingView = _launchView;
}
 
- (BOOL)hidesNavigationBarDuringPresentation {
    return self.searchController.hidesNavigationBarDuringPresentation;
}
 
- (void)setHidesNavigationBarDuringPresentation:(BOOL)hidesNavigationBarDuringPresentation {
    self.searchController.hidesNavigationBarDuringPresentation = hidesNavigationBarDuringPresentation;
}
 
- (void)setQmui_prefersStatusBarHiddenBlock:(BOOL (^)(void))qmui_prefersStatusBarHiddenBlock {
    [super setQmui_prefersStatusBarHiddenBlock:qmui_prefersStatusBarHiddenBlock];
    self.searchController.qmui_prefersStatusBarHiddenBlock = qmui_prefersStatusBarHiddenBlock;
}
 
- (void)setQmui_preferredStatusBarStyleBlock:(UIStatusBarStyle (^)(void))qmui_preferredStatusBarStyleBlock {
    [super setQmui_preferredStatusBarStyleBlock:qmui_preferredStatusBarStyleBlock];
    self.searchController.qmui_preferredStatusBarStyleBlock = qmui_preferredStatusBarStyleBlock;
}
 
#pragma mark - QMUIEmptyView
 
- (void)showEmptyView {
    // 搜索框文字为空时,界面会显示遮罩,此时不需要显示emptyView了
    // 为什么加这个是因为当搜索框被点击时(进入搜索状态)会触发searchController:updateResultsForSearchString:,里面如果直接根据搜索结果为空来showEmptyView的话,就会导致在遮罩层上有emptyView出现,要么在那边showEmptyView之前判断一下searchBar.text.length,要么在showEmptyView里判断,为了方便,这里选择后者。
    if (self.searchBar.text.length <= 0) {
        return;
    }
    
    [super showEmptyView];
    
    // 格式化样式,以适应当前项目的需求
    self.emptyView.backgroundColor = TableViewBackgroundColor ?: UIColorWhite;
    if ([self.searchResultsDelegate respondsToSelector:@selector(searchController:willShowEmptyView:)]) {
        [self.searchResultsDelegate searchController:self willShowEmptyView:self.emptyView];
    }
    
    if (self.searchController) {
        UIView *superview = self.searchController.searchResultsController.view;
        [superview addSubview:self.emptyView];
    } else {
        QMUIAssert(NO, NSStringFromClass(self.class), @"QMUISearchController 无法为 emptyView 找到合适的 superview");
    }
    
    [self layoutEmptyView];
}
 
#pragma mark - <QMUISearchResultsTableViewControllerDelegate>
 
- (void)didLoadTableViewInSearchResultsTableViewController:(QMUISearchResultsTableViewController *)viewController {
    if ([self.searchResultsDelegate respondsToSelector:@selector(searchController:didLoadSearchResultsTableView:)]) {
        [self.searchResultsDelegate searchController:self didLoadSearchResultsTableView:viewController.tableView];
    }
}
 
#pragma mark - <UISearchResultsUpdating>
 
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if ([self.searchResultsDelegate respondsToSelector:@selector(searchController:updateResultsForSearchString:)]) {
        [self.searchResultsDelegate searchController:self updateResultsForSearchString:searchController.searchBar.text];
    }
}
 
#pragma mark - <UISearchControllerDelegate>
 
- (void)willPresentSearchController:(UISearchController *)searchController {
    if (self.searchController.qmui_prefersStatusBarHiddenBlock || self.searchController.qmui_preferredStatusBarStyleBlock) {
        [self.searchController setNeedsStatusBarAppearanceUpdate];
    }
    if ([self.searchResultsDelegate respondsToSelector:@selector(willPresentSearchController:)]) {
        [self.searchResultsDelegate willPresentSearchController:self];
    }
}
 
- (void)didPresentSearchController:(UISearchController *)searchController {
    if ([self.searchResultsDelegate respondsToSelector:@selector(didPresentSearchController:)]) {
        [self.searchResultsDelegate didPresentSearchController:self];
    }
}
 
- (void)willDismissSearchController:(UISearchController *)searchController {
    if (self.searchController.qmui_prefersStatusBarHiddenBlock || self.searchController.qmui_preferredStatusBarStyleBlock) {
        [self.searchController setNeedsStatusBarAppearanceUpdate];
    }
    if ([self.searchResultsDelegate respondsToSelector:@selector(willDismissSearchController:)]) {
        [self.searchResultsDelegate willDismissSearchController:self];
    }
}
 
- (void)didDismissSearchController:(UISearchController *)searchController {
    // 退出搜索必定先隐藏emptyView
    [self hideEmptyView];
    
    if ([self.searchResultsDelegate respondsToSelector:@selector(didDismissSearchController:)]) {
        [self.searchResultsDelegate didDismissSearchController:self];
    }
}
 
@end
 
EndIgnoreDeprecatedWarning
 
@implementation QMUICommonTableViewController (Search)
 
QMUISynthesizeIdStrongProperty(searchController, setSearchController)
QMUISynthesizeIdStrongProperty(searchBar, setSearchBar)
 
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        ExtendImplementationOfVoidMethodWithoutArguments([QMUICommonTableViewController class], @selector(initSubviews), ^(QMUICommonTableViewController *selfObject) {
            [selfObject initSearchController];
        });
        
        ExtendImplementationOfVoidMethodWithSingleArgument([QMUICommonTableViewController class], @selector(viewWillAppear:), BOOL, ^(QMUICommonTableViewController *selfObject, BOOL firstArgv) {
            if (!selfObject.searchController.tableView.allowsMultipleSelection) {
                [selfObject.searchController.tableView qmui_clearsSelection];
            }
        });
        
        ExtendImplementationOfVoidMethodWithoutArguments([QMUICommonTableViewController class], @selector(showEmptyView), ^(QMUICommonTableViewController *selfObject) {
            if ([selfObject shouldHideSearchBarWhenEmptyViewShowing] && selfObject.tableView.tableHeaderView == selfObject.searchBar) {
                selfObject.tableView.tableHeaderView = nil;
            }
        });
        
        ExtendImplementationOfVoidMethodWithoutArguments([QMUICommonTableViewController class], @selector(hideEmptyView), ^(QMUICommonTableViewController *selfObject) {
            if (selfObject.shouldShowSearchBar && [selfObject shouldHideSearchBarWhenEmptyViewShowing] && selfObject.tableView.tableHeaderView == nil) {
                [selfObject initSearchController];
                // 隐藏 emptyView 后重新设置 tableHeaderView,会导致原先 shouldHideTableHeaderViewInitial 隐藏头部的操作被重置,所以下面的 force 参数要传 YES
                // https://github.com/Tencent/QMUI_iOS/issues/128
                selfObject.tableView.tableHeaderView = selfObject.searchBar;
                [selfObject hideTableHeaderViewInitialIfCanWithAnimated:NO force:YES];
            }
        });
    });
}
 
static char kAssociatedObjectKey_shouldShowSearchBar;
- (void)setShouldShowSearchBar:(BOOL)shouldShowSearchBar {
    BOOL isValueChanged = self.shouldShowSearchBar != shouldShowSearchBar;
    if (!isValueChanged) {
        return;
    }
    
    objc_setAssociatedObject(self, &kAssociatedObjectKey_shouldShowSearchBar, @(shouldShowSearchBar), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    if (shouldShowSearchBar) {
        [self initSearchController];
    } else {
        if (self.searchBar) {
            if (self.tableView.tableHeaderView == self.searchBar) {
                self.tableView.tableHeaderView = nil;
            }
            [self.searchBar removeFromSuperview];
            self.searchBar = nil;
        }
        if (self.searchController) {
            self.searchController.searchResultsDelegate = nil;
            self.searchController = nil;
        }
    }
}
 
- (BOOL)shouldShowSearchBar {
    return [((NSNumber *)objc_getAssociatedObject(self, &kAssociatedObjectKey_shouldShowSearchBar)) boolValue];
}
 
- (void)initSearchController {
    if ([self isViewLoaded] && self.shouldShowSearchBar && !self.searchController) {
        self.searchController = [[QMUISearchController alloc] initWithContentsViewController:self resultsTableViewStyle:self.tableView.style];
        self.searchController.searchResultsDelegate = self;
        self.searchController.searchBar.placeholder = @"搜索";
        self.searchController.searchBar.qmui_usedAsTableHeaderView = YES;// 以 tableHeaderView 的方式使用 searchBar 的话,将其置为 YES,以辅助兼容一些系统 bug
        self.tableView.tableHeaderView = self.searchController.searchBar;
        self.searchBar = self.searchController.searchBar;
    }
}
 
- (BOOL)shouldHideSearchBarWhenEmptyViewShowing {
    return NO;
}
 
#pragma mark - <QMUISearchControllerDelegate>
 
- (void)searchController:(QMUISearchController *)searchController updateResultsForSearchString:(NSString *)searchString {
    
}
 
@end