【Objective-C】UISearchControllerを実装してみた【Xcode10.2対応】

こういう人に向けて発信しています。
・UISearchControllerとは何か気になる人
・UISearchBarの挙動と比較したい人
・Objective-C初心者

実際のアプリイメージ

コード(Objective-C)

#import "TableViewController.h"

@interface TableViewController ()
@property (strong, nonatomic) UISearchController *searchController;

@end

@implementation TableViewController

#pragma mark - ViewController ライフサイクル

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UISearchController *searchController = [[ UISearchController alloc ] initWithSearchResultsController:nil ];
    searchController.searchResultsUpdater = self;
    searchController.hidesNavigationBarDuringPresentation = NO;
    searchController.dimsBackgroundDuringPresentation = NO;
    searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    [searchController.searchBar sizeToFit];
    self.tableView.tableHeaderView = searchController.searchBar;
    
    self.searchController = searchController;
}

#pragma mark - UISearchController

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    // tableViewに表示する内容を抽出します。
    // 入力されたテキストは、searchController.searchBar.text として取り出せます。
    // フィルタ作業ができたら、tableViewをreloadして終わりです
    NSLog(@"%@",searchController.searchBar.text);
    [self.tableView reloadData];
    
}

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //標準で用意されているTableViewを利用する場合。
    NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"このセルは%ld番目のセルになります!", (long)indexPath.row];
    return cell;
}


いいなと思ったら応援しよう!