搜索条(UISearchBar)

2017-03-08  本文已影响0人  焉逢12
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.
    }


}
上一篇下一篇

猜你喜欢

热点阅读