搜索條(UISearchBar)

import UIKit

class ViewController: UIViewController,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var search: UISearchBar!
    
    @IBOutlet weak var tableView: UITableView!
    
    var Arr :[String]?
    var searchArr :[String]?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Arr = ["1","2","3","4","5","6"]
        search.delegate = self
        tableView.delegate = self
        tableView.dataSource = self
        
        search.barTintColor = UIColor.blue
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")

        //默認加載所有數據
        searchArr = NSArray(array: Arr!) as? [String]
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (searchArr?.count)!
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
        cell.textLabel?.text = searchArr?[indexPath.row]
        return cell
    }
    // 搜索代理UISearchBarDelegate方法,每次改變搜索內容時都會調用
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        //輸入內容為空時
        if searchText.isEmpty {
            searchArr = Arr
        }
        else
        {
            searchArr = []
            for str in Arr! {
                //轉換小寫
                if str.lowercased().hasPrefix(searchText.lowercased()){
                    searchArr?.append(str)
                }
            }
            
            
        }
        tableView.reloadData()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1。Options ShowsSearchResultsButton:勾選該復選框后,將會在搜索文本框的右端顯示一...
    nalis風閱讀 426評論 0 0
  • 1。Options ShowsSearchResultsButton:勾選該復選框后,將會在搜索文本框的右端顯示一...
    nalis風閱讀 290評論 0 0
  • AppDelegate.m ViewController *theVc = [[ViewController al...
    leaderleader閱讀 106評論 0 0
  • 最美不過夕陽紅,也許有人會有疑問,難道日出不漂亮嗎?當然漂亮,還記得當時大學畢業時去青島玩,運氣還不錯,看到了海上...
    紫彤嘻嘻閱讀 273評論 0 0
  • 原以為他這種經常出差的日子不會太久,可事實證明我OUT了,這個工作他一做就是15年,也就是說我們聚少離多的日子一過...
    真冉閱讀 226評論 2 1