swift-教你如何實現導航上的UISearchController動畫效果。


   這個代碼片段是我這周我從網上找了各種資料然后經過自己的修改終於弄好了導航的上下動畫效果:

step1:==>因為這個搜索要有動畫效果,所以這個頁面必須要有一個導航控制器:

//1.自定義創建導航控制器

這個頁面我是從其他頁面跳轉過來的,跳轉之前我自定義了一個導航控制器:

   let actionSearchTable=searchTable();

        let navVC = UINavigationController(rootViewController: actionSearchTable);

        navVC.navigationBar.barStyle = UIBarStyle.BlackTranslucent;

        self.presentViewController(navVC, animated: true, completion: nil);

//2.點擊搜索跳轉到 searchTable.swift,這個頁面我繼承的是 UITableViewController,而不是UiViewController,一定要注意,不然每當點擊一次搜索取消的時候table上面會多出一片空白,這個原理我還不是太明白,如果你們發現了其中的原理希望能指點一二。

這個表格的數據源我引用的是一個txt文件。格式如下圖:

 

//
//  searchResultTable.swift
//  搜索框
//
//  Created by 盧洋 on 15/11/6.
//  Copyright © 2015年 奈文摩爾. All rights reserved.
//

import UIKit

class searchTable: UITableViewController,UISearchBarDelegate{
    lazy var dismissBtn: UIButton = { UIButton(frame: CGRectMake(0, 0, 24, 24)) }();//返回按鈕
    
    var itemsString:[String]!
    var searcher:UISearchController!
    var searchBars:UISearchBar?
    
    struct SearchControllerRestorableState {
        var wasActive = false
        var wasFirstResponder = false
    }
    var restoredState = SearchControllerRestorableState();
    
    //初始化函數
    override func viewDidLoad() {
        super.viewDidLoad();
        self.title="查找商家";
        initView();
        
    }
    
    //初始化UI
    func initView(){
        dismissBtnPrepare();
        //創建Table
        self.tableView=UITableView(frame: CGRectMake(0, 80, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height));
        self.tableView.delegate=self;
        self.tableView.dataSource=self;
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cells")
        
        //1.讀取表格數據
        let tablePath = NSBundle.mainBundle().pathForResource("states", ofType: "txt")!;
        let tableData=try! NSString(contentsOfFile: tablePath, encoding: NSUTF8StringEncoding);
        itemsString = tableData.componentsSeparatedByString("\n") as [String];
        
        let src = searchResultTable(data: itemsString)
        searcher = UISearchController(searchResultsController: src)
        
        searcher.searchResultsUpdater = src;
        //獲取焦點時有陰影效果
        searcher.dimsBackgroundDuringPresentation=true;
        //獲取焦點導航向上移的動畫效果
        searcher.hidesNavigationBarDuringPresentation=true;
        searchBars = searcher.searchBar
        tableView.tableHeaderView = searchBars
        searchBars?.delegate=self;
        searchBars?.placeholder="輸入商家名稱";
        //取消按鈕顏色和文本框光標顏色
        searchBars?.tintColor=UIColor.blueWithTabbar();
        //搜索框背景顏色
        //searchBars?.barTintColor=UIColor.blackColor();
        searcher.searchBar.sizeToFit();
        self.tableView.reloadData();
     //背景充滿導航 definesPresentationContext
= true; } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Restore the searchController's active state. if restoredState.wasActive { searcher.active = restoredState.wasActive restoredState.wasActive = false if restoredState.wasFirstResponder { searcher.searchBar.becomeFirstResponder() restoredState.wasFirstResponder = false } } } override func viewDidDisappear(animated: Bool) { super.viewDidAppear(animated); //2.3將狀態欄變為白色 UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent; } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemsString.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cells", forIndexPath: indexPath) cell.textLabel!.text = itemsString[indexPath.row]; return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //取消選中的樣式 tableView.deselectRowAtIndexPath(indexPath, animated: true); //獲取點擊的行索引 if(indexPath.row == 0){ } } /** 返回按鈕 */ func dismissBtnPrepare(){ dismissBtn.setImage(UIImage(named: "img.bundle/cancel"), forState: UIControlState.Normal) dismissBtn.addTarget(self, action: "dismissLogin", forControlEvents: UIControlEvents.TouchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: dismissBtn) } /** 釋放當前頁面 */ func dismissLogin(){ self.dismissViewControllerAnimated(true, completion: nil) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { print("b"); //2.3將狀態欄變為白色 UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent; } //搜索框開始編輯事件 func searchBarTextDidBeginEditing(searchBar: UISearchBar) { //2.3將狀態欄變為白色 UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default; } func searchBarTextDidEndEditing(searchBar: UISearchBar) { //2.3將狀態欄變為白色 UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent; } }

//3.搜索結果頁面  searchResultTable.swift

//
//  searchResultTable2.swift
//  searchBarDemo
//
//  Created by 盧洋 on 15/11/6.
//  Copyright © 2015年 奈文摩爾. All rights reserved.
//

import Foundation
import UIKit
class searchResultTable:UITableViewController,UISearchResultsUpdating{
    var tableData:UITableView!;
    var originalData:[String]!                  //原數據
    var filteredData:[String]!                  //過濾數據
    
    override func viewDidLoad() {
        super.viewDidLoad();
        self.title="輸入商家名稱";
        initView()
    }
    init(data:[String]){
        originalData = data
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //初始化UI
    func initView(){

        //創建Table
        tableData=UITableView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height));
        self.view.addSubview(tableData);
        //tableData.backgroundColor=UIColor.redColor();
        tableData.delegate=self;
        tableData.dataSource=self;
        tableData.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cells")
        
    }
    
     override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return filteredData.count
    }

     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cells", forIndexPath: indexPath)
        
        cell.textLabel!.text = originalData[indexPath.row];
        
        return cell
    }

    func updateSearchResultsForSearchController(searchController: UISearchController) {
        let searchBar=searchController.searchBar;
        let target=searchBar.text;
        filteredData = originalData.filter()
            {
                
                s in
                var options = NSStringCompareOptions.CaseInsensitiveSearch
                if searchController.searchBar.selectedScopeButtonIndex == 0
                {
                    options = options.union(.AnchoredSearch)
                }
                let found = s.rangeOfString(target!, options: options)
                
                return (found != nil)
        }
        tableData.reloadData()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning();
    }

}

 

好最后效果圖如下:但是其中的字符串過濾有一點點問題,解決了一定要告訴我。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM