LoginSignup
50
44

More than 3 years have passed since last update.

iOS8以降はUISearchControllerを使え

Last updated at Posted at 2015-10-18

TableViewに検索フォームを付ける場合は、UISearchDisplayControllerを実装していましたがiOS8からはUISearchControllerを使えとなってます。

古いプロジェクトを放置しっぱなしだと、この手の新しいAPIで作り変えるのは非常に萎える作業ですが、頑張ってついて行きたいと思います。

UISearchControllerですが、StoryBoardではなく、コードで実装します。
ViewControllerの中で、

ViewController.m
@property (strong, nonatomic) UISearchController *searchController;

とします。次にUISearchControllerをtableViewに追加します。tableViewはStoryboardで設置しておきます。

ViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    UISearchController *searchController = [[ UISearchController alloc ] initWithSearchResultsController:nil ];
    searchController.searchResultsUpdater = self;
    searchController.hidesNavigationBarDuringPresentation = false;
    searchController.dimsBackgroundDuringPresentation = false;
    searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
    [searchController.searchBar sizeToFit];
    self.tableView.tableHeaderView = searchController.searchBar;

    self.searchController = searchController;
}
ViewController.swift
override func viewDidLoad() {
    super.viewDidLoad()

    searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.searchBar.sizeToFit()

}

これだけで、表示はできますが、フォームをクリックすると落ちるので、下記を追加

ViewController.m
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    // tableViewに表示する内容を抽出します。
  // 入力されたテキストは、searchController.searchBar.text として取り出せます。
    // フィルタ作業ができたら、tableViewをreloadして終わりです

    [self.tableView reloadData];

}

各tableViewの中での処理は単にself.searchController.activeがtrueかfalseをみれば、検索結果を表示しているのかそうではないかが判断つきます。

ViewController.m
if ( self.searchController.active ) {
    // 検索結果表示
}

この辺のdelegate処理の話です。

ViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

UISearchDisplayControllerでも似たような感じで処理しますが、呼ばれるのがひとつだけなのでちょっと楽になった感じですね。
そうそう、検索結果を選択して何かしようとする場合は、
self.searchController.active = false;
とするのをお忘れなく。

50
44
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
50
44