UISearchController使用記錄

1 UISearchController使用

可用于上傳文件的文件列表顯示頁(yè)

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;//暫時(shí)只支持一個(gè)文件
@property (nonatomic, strong) UploadFileInfo *file;
@property (nonatomic, strong) NSArray<UploadFileInfo *> *fileArr;//暫時(shí)只支持一個(gè)文件

@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變大的問(wèn)題
    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;
}

//點(diǎn)擊進(jìn)入文件詳情頁(yè)
- (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];
}

//文件預(yù)覽頁(yè)回調(diào)
#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
  • 說(shuō)明:
    1)UISearchController使用時(shí)作為HeadView饭耳,需要和UItableView配合使用。
    2)文件預(yù)覽有多種方式欠痴,這里使用了UIDocumentInteractionController最爬。

搜索結(jié)果頁(yè)

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

補(bǔ)充:擴(kuò)大UIView的點(diǎn)擊范圍

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相關(guān)

UISearchController

UISearchController沒(méi)有隱藏導(dǎo)航欄

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];

這里需要設(shè)置nil溉跃,而不是self。

hidesNavigationBarDuringPresentation不生效

SearchResultsController開(kāi)啟新頁(yè)面時(shí)searchBar向上位移

監(jiān)聽(tīng)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;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市痛单,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌劲腿,老刑警劉巖旭绒,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異焦人,居然都是意外死亡挥吵,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門花椭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)忽匈,“玉大人,你說(shuō)我怎么就攤上這事矿辽〉ぴ剩” “怎么了郭厌?”我有些...
    開(kāi)封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)雕蔽。 經(jīng)常有香客問(wèn)我折柠,道長(zhǎng),這世上最難降的妖魔是什么批狐? 我笑而不...
    開(kāi)封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任扇售,我火速辦了婚禮,結(jié)果婚禮上嚣艇,老公的妹妹穿的比我還像新娘承冰。我一直安慰自己,他們只是感情好髓废,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布巷懈。 她就那樣靜靜地躺著,像睡著了一般慌洪。 火紅的嫁衣襯著肌膚如雪顶燕。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天冈爹,我揣著相機(jī)與錄音涌攻,去河邊找鬼。 笑死频伤,一個(gè)胖子當(dāng)著我的面吹牛恳谎,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播憋肖,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼因痛,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了岸更?” 一聲冷哼從身側(cè)響起鸵膏,我...
    開(kāi)封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎怎炊,沒(méi)想到半個(gè)月后谭企,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡评肆,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年债查,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瓜挽。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡盹廷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出久橙,到底是詐尸還是另有隱情速和,我是刑警寧澤歹垫,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站颠放,受9級(jí)特大地震影響排惨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜碰凶,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一暮芭、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧欲低,春花似錦辕宏、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至腊瑟,卻和暖如春聚假,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背闰非。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工膘格, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人财松。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓瘪贱,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親辆毡。 傳聞我的和親對(duì)象是個(gè)殘疾皇子菜秦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容