UISearchController使用记录

1 UISearchController使用

可用于上传文件的文件列表显示页

UploadFileViewController.h

@interface UploadFileViewController : UIViewController

@end

UploadFileViewController.m
核心代码

@interface UploadFileViewController () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, SearchResultViewControllerDelegate, UIDocumentInteractionControllerDelegate/*, UISearchControllerDelegate, UISearchResultsUpdating, UITextFieldDelegate*/>

@property (nonatomic, strong) UIView *navigatorView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIImageView *titleImageView;
@property (nonatomic, strong) UploadFileTypeView *typeView;
//@property (nonatomic, strong) NSDictionary *file;
//@property (nonatomic, strong) NSArray<NSDictionary *> *fileArr;//暂时只支持一个文件
@property (nonatomic, strong) UploadFileInfo *file;
@property (nonatomic, strong) NSArray<UploadFileInfo *> *fileArr;//暂时只支持一个文件

@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) SearchResultViewController *resultController;

//@property (nonatomic, strong) NSArray<UploadFileInfo *> *resultArr;

@end

@implementation UploadFileViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupData];
    
    [self setupView];
}

- (void)setupView
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.navigatorView];
    [self.view addSubview:self.backButton];
    [self.view addSubview:self.confirmButton];
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.titleImageView];
    [self.view addSubview:self.tableview];

    CGRect rectNavi = self.navigatorView.frame;
    double bottom = rectNavi.origin.y + rectNavi.size.height + 8;
    
    CGRect rectView = self.tableview.frame;
    CGFloat x = rectView.origin.x;
    CGFloat y = bottom;
    CGFloat width = rectView.size.width;
    CGFloat height = rectView.size.height - y;
    self.tableview.frame = CGRectMake(x, y, width, height);

    CGPoint center = self.navigatorView.center;
    self.backButton.center = CGPointMake(self.backButton.center.x, center.y);
    self.confirmButton.center = CGPointMake(self.confirmButton.center.x, center.y);
    self.titleLabel.center = CGPointMake(center.x - self.titleImageView.frame.size.width / 2 - 2, center.y);
    self.titleImageView.center = CGPointMake(center.x + self.titleLabel.frame.size.width / 2 + 2, center.y);
    
    self.resultController = [[SearchResultViewController alloc] init];
    self.resultController.fileArr = self.fileArr;
    self.resultController.delegate = self;
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultController];
    self.searchController.searchResultsUpdater = self.resultController;
    self.searchController.delegate = self.resultController;
    
    self.searchController.hidesNavigationBarDuringPresentation = YES;
    self.definesPresentationContext = YES;
    self.searchController.definesPresentationContext = YES;
    self.searchController.searchBar.delegate = self;

    self.resultController.mainController = self;
    
    //处理添加UISearchController后UITableView的ContentSize变大的问题
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.searchController.searchBar.bounds.size.width, self.searchController.searchBar.bounds.size.height)];
    [headerView addSubview:self.searchController.searchBar];
    self.tableview.tableHeaderView = headerView;
}

//点击进入文件详情页
- (void)invokeDetailByData:(id)data
{
    NSLog(@"app: invokeDetailByData:%@", data);
    
    UploadFileInfo *info = (UploadFileInfo *)data;
    
    UIDocumentInteractionController *docVC = [[UIDocumentInteractionController alloc] init];
    docVC.URL = [NSURL fileURLWithPath:info.path];
    docVC.delegate = self;
    [docVC presentPreviewAnimated:YES];
}

//文件预览页回调
#pragma mark - UIDocumentInteractionControllerDelegate

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
    return CGRectMake(0, 30, self.view.bounds.size.width, self.view.bounds.size.height);
}

- (void)documentInteractionControllerWillBeginPreview:(UIDocumentInteractionController *)controller
{
    NSLog(@"app: docVC will begin");

}

- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller
{
    NSLog(@"app: docVC did end");
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.fileArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UploadFileTableViewCell *cell = (UploadFileTableViewCell *)[tableView dequeueReusableCellWithIdentifier:[UploadFileTableViewCell cellWithReuseIdentifier] forIndexPath:indexPath];
    
    UploadFileInfo *info = self.fileArr[indexPath.row];
    
    [cell updateCellWithData:info];
    
    [cell updateSelectStatus:info.selected];
    if (info.selected) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
    
    __weak typeof(self) weakSelf = self;
    cell.detailBlock = ^(id  _Nonnull data) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf invokeDetailByData:data];
    };
    
//    NSLog(@"app: cell indexPath.row:%ld, cell:%@, info.selected:%@", (long)indexPath.row, cell, @(info.selected));

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UploadFileTableViewCell *cell = (UploadFileTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];

    UploadFileInfo *info = self.fileArr[indexPath.row];
    
    if (info.selected) {
        info.selected = NO;
        self.file = nil;
    } else {
        info.selected = YES;
        self.file = info;
    }
    [cell updateSelectStatus:info.selected];
    [self checkConfrimButtonStatus];
    NSLog(@"app: select indexPath.row:%ld, cell:%@, info.selected:%@", (long)indexPath.row, cell, @(info.selected));
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    UploadFileTableViewCell *cell = (UploadFileTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    UploadFileInfo *info = self.fileArr[indexPath.row];
    
    info.selected = NO;
    [cell updateSelectStatus:info.selected];
    NSLog(@"app: un-select indexPath.row:%ld, cell:%@, info.selected:%@", (long)indexPath.row, cell, @(info.selected));

}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"app: seearchBar cancel oooooo");
        
    if (self.resultController.file) {
        //取消之前的
        if (self.file != self.resultController.file) {
            self.file.selected = NO;
        }
        
        self.file = self.resultController.file;
        self.resultController.file = nil;//清理掉
        [self checkConfrimButtonStatus];
    } else {
        if (!self.file.selected) {
            self.file = nil;
        }
    }
    [self.tableview reloadData];
}

#pragma mark - SearchResultViewControllerDelegate

- (void)scrollViewDidScrollAction
{
    [self.searchController.searchBar endEditing:YES];
}

- (void)openFileDetailByData:(id)data
{
    [self invokeDetailByData:data];
}

@end
  • 说明:
    1)UISearchController使用时作为HeadView,需要和UItableView配合使用。
    2)文件预览有多种方式,这里使用了UIDocumentInteractionController。

搜索结果页

SearchResultViewController.h

@protocol SearchResultViewControllerDelegate <NSObject>

@optional
- (void)scrollViewDidScrollAction;
- (void)openFileDetailByData:(id)data;

@end

@interface SearchResultViewController : UIViewController <UISearchControllerDelegate, UISearchResultsUpdating>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) UIViewController *mainController;

@property (nonatomic, strong) NSArray<UploadFileInfo *> *fileArr;
@property (nonatomic, strong) UploadFileInfo *file;

@property (nonatomic, weak) id<SearchResultViewControllerDelegate> delegate;

@end

SearchResultViewController.m
核心代码

@interface SearchResultViewController () <UITableViewDelegate, UITableViewDataSource/*, UIDocumentInteractionControllerDelegate*/>

@property (nonatomic, strong) NSArray<UploadFileInfo *> *resultArr;

@end

@implementation SearchResultViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupData];
    [self setupView];
}

- (void)setupData
{
    self.resultArr = self.fileArr;
}

- (void)setupView
{
    self.definesPresentationContext = YES;

    [self.view addSubview:self.tableview];
}

#pragma mark - UISearchControllerDelegate

- (void)willPresentSearchController:(UISearchController *)searchController
{
    NSLog(@"app: willPresentSearchController");
    
    CGRect mainrect = self.mainController.view.frame;
    [UIView animateWithDuration:0.5 animations:^{
        self.mainController.view.frame = CGRectMake(0, -24, mainrect.size.width, mainrect.size.height);
    }];
}


- (void)didPresentSearchController:(UISearchController *)searchController
{
    NSLog(@"app: didPresentSearchController");
}

- (void)willDismissSearchController:(UISearchController *)searchController
{
    CGRect mainrect = searchController.view.frame;
    [UIView animateWithDuration:0.5 animations:^{
        self.mainController.view.frame = CGRectMake(0, 0, mainrect.size.width, mainrect.size.height);
    }];
}

- (void)didDismissSearchController:(UISearchController *)searchController
{
    
}

#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *searchString = searchController.searchBar.text;
    NSLog(@"app: searchString:%@", searchString);
    
    if (searchString.length) {
          __block NSInteger index = -1;
        NSMutableArray<UploadFileInfo *> *array = [NSMutableArray array];
        [self.fileArr enumerateObjectsUsingBlock:^(UploadFileInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.name containsString:searchString]) {
                [array addObject:obj];
                if (obj.selected) {
                    index = array.count - 1;
                }
            }
        }];
        self.resultArr = array.copy;
        
        [self.tableview reloadData];
    }
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UploadFileTableViewCell *cell = (UploadFileTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"UPloadFileResult" forIndexPath:indexPath];
    
    UploadFileInfo *info = self.resultArr[indexPath.row];
    [cell updateCellWithData:info];
    
    __weak typeof(self) weakSelf = self;
    cell.detailBlock = ^(id  _Nonnull data) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf invokeDetailByData:data];
    };
    
    [cell updateSelectStatus:info.selected];
    if (info.selected) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UploadFileTableViewCell *cell = (UploadFileTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    UploadFileInfo *info = self.resultArr[indexPath.row];
    if (info.selected) {
        info.selected = NO;
        self.file = nil;
    } else {
        info.selected = YES;
        self.file = info;
    }
    [cell updateSelectStatus:info.selected];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UploadFileTableViewCell *cell = (UploadFileTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    UploadFileInfo *info = self.resultArr[indexPath.row];
    info.selected = NO;
    [cell updateSelectStatus:info.selected];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (decelerate) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(scrollViewDidScrollAction)]) {
              [self.delegate scrollViewDidScrollAction];
          }
    }
}

@end

Model

UploadFileInfo.h

@interface UploadFileInfo : NSObject

@property (nonatomic, strong) NSString *path;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSDate *createDate;
@property (nonatomic, strong) NSDate *modifyDate;
@property (nonatomic, strong) NSNumber *size;
@property (nonatomic, assign) BOOL ios;
@property (nonatomic, assign) BOOL selected;

+ (UploadFileInfo *)getUploadFileInfoByDictionary:(NSDictionary *)dic;
- (NSDictionary *)convertToDictionary;

@end

UploadFileInfo.m

@implementation UploadFileInfo

+ (UploadFileInfo *)getUploadFileInfoByDictionary:(NSDictionary *)dic
{
    if (!dic) {
        return nil;
    }
    UploadFileInfo *info = [UploadFileInfo new];
    info.path = dic[@"path"];
    info.name = dic[@"name"];
    info.size = dic[@"size"];
    info.ios = YES;
    info.createDate = dic[@"createDate"];
    info.modifyDate = dic[@"modifyDate"];
    info.selected = NO;
    return info;
}

- (NSDictionary *)convertToDictionary
{
    NSDate *currentDate = [NSDate date];
    return @{
        @"path": self.path.length ? self.path : @"",
        @"name": self.name.length ? self.name : @"",
        @"size": self.size ? self.size : @(0),
        @"ios": @(YES),
        @"modifyDate": self.modifyDate ? self.modifyDate : currentDate,
        @"createDate": self.createDate ? self.createDate : currentDate
    };
}

@end

补充:扩大UIView的点击范围

UploadFileDetainImageView.h

@interface UploadFileDetainImageView : UIImageView

@end

UploadFileDetainImageView.m

@implementation UploadFileDetainImageView

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    return CGRectContainsPoint(CGRectInset(self.bounds, -5, -5), point);
}

@end

2 UISearchController相关

UISearchController

UISearchController没有隐藏导航栏

ios自定义SearchController

UISearchController显示崩溃

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modal view controller on itself. Presenting controller is <UISearchController: 0x107937a00>.'

  • 处理:
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];

这里需要设置nil,而不是self。

hidesNavigationBarDuringPresentation不生效

SearchResultsController开启新页面时searchBar向上位移

监听searchBar的clear按钮事件

uisearchcontroller适配

uisearchcontroller添加后tableview的contentsize变大

  • 处理:
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.searchController.searchBar.height)];
    [headerView addSubview:self.searchController.searchBar];
    self.tableView.tableHeaderView = headerView;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,839评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,543评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,116评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,371评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,384评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,111评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,416评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,053评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,558评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,007评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,117评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,756评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,324评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,315评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,539评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,578评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,877评论 2 345

推荐阅读更多精彩内容