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

來源:互聯網
上載者:User

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 UIKitclass 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 Foundationimport UIKitclass 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();    }}

 

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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.