1. 程式人生 > >iOS開發之高階檢視—— UISearchController

iOS開發之高階檢視—— UISearchController

     UISearchController控制元件正好了UISearchBar、UITableView,而且內部提供了良好的封裝,可以方便的實現搜尋列表。

     建立一個工程,並且刪除原來的ViewController.h和ViewController.m,重新建立一個檔案,命名為ViewController,繼承UITableViewController。

     AppDelegate.m

//
//  AppDelegate.m
//  UISearchControllerDemo
//
//  Created by Apple on 16/5/26.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    ViewController* viewController = [[ViewController alloc] initWithStyle:UITableViewStyleGrouped];
    
    self.window.rootViewController = viewController;
    
    [self.window makeKeyAndVisible];
    return YES;
    return YES;
}


@end

  ViewController.h
//
//  ViewController.h
//  UISearchControllerDemo_c
//
//  Created by apple on 15/7/10.
//  Copyright (c) 2015年 fkit.org. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UITableViewController <UISearchResultsUpdating,UISearchBarDelegate>

@end


 ViewController.m


//
//  ViewController.m
//  UISearchControllerDemo
//
//  Created by Apple on 16/5/26.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

// ? 必須定義成全域性變數
UISearchController *searchController;
// 儲存原始表格資料的NSArray物件。
NSArray * tableData;
// 儲存搜尋結果資料的NSArray物件。
NSArray* searchData;

- (void)viewDidLoad {
    NSLog(@"viewDidLoad --> 裝載控制元件");
    [super viewDidLoad];
    
    // 初始化原始表格資料
    tableData = [NSArray arrayWithObjects:@"Java講義",
                 @"輕量級Java EE企業應用實戰",
                 @"Android講義",
                 @"Ajax講義",
                 @"HTML5/CSS3/JavaScript講義",
                 @"iOS講義",
                 @"XML講義",
                 @"經典Java EE企業應用實戰"
                 @"Java入門與精通",
                 @"Java基礎教程",
                 @"學習Java",
                 @"Objective-C基礎" ,
                 @"Ruby入門與精通",
                 @"iOS開發教程" , nil];
    
    // 註冊
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuseIdentifier"];
    
    // UISearchController控制元件整合了UISearchBar,而且內部提供了良好的封裝,可以方便的實現搜尋列表。
    searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    // 注意:必須設定searchBar的大小
    searchController.searchBar.frame = CGRectMake(0, 88, 100, 66);
    // 設定提示
    //    searchController.searchBar.prompt = @"查詢圖書";
    searchController.searchBar.placeholder = @"請輸入字元";
    // 顯示CancelButton
    searchController.searchBar.showsCancelButton = true;
    
    // 設定這個物件(self)負責更新搜尋結果控制器的內容
    searchController.searchResultsUpdater = self;
    // 搜尋結果的背景
    //    searchController.dimsBackgroundDuringPresentation = NO;
    
    searchController.searchBar.delegate = self;
    
    self.tableView.tableHeaderView = searchController.searchBar;
    
    
}

-(void) viewDidAppear:(BOOL)animated{
    //    self.tableView.frame = [UIScreen mainScreen].applicationFrame;
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSLog(@"updateSearchResultsForSearchController --> ");
    // 定義搜尋謂詞
    NSPredicate* pred = [NSPredicate predicateWithFormat:
                         @"SELF CONTAINS[c] %@" , searchController.searchBar.text];
    // 使用謂詞過濾tableData陣列,返回新陣列searchData
    searchData = [tableData filteredArrayUsingPredicate:pred];
    NSLog(@"searchData -->%lu",[searchData count]);
    // 重新整理資料(顯示新陣列)
    [self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarCancelButtonClicked --> ");
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (searchController.active) {
        return [searchData count];
    }else{
        return [tableData count];
    }
    
}

/**/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    
    if (searchController.active) {
        cell.textLabel.text = [searchData objectAtIndex:indexPath.row];
    }else{
        cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
    }
    
    return cell;
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

     效果圖如下: