美文网首页
搜索条(UISearchBar)

搜索条(UISearchBar)

作者: 焉逢12 | 来源:发表于2017-03-08 14:56 被阅读0次
    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.
        }
    
    
    }
    

    相关文章

      网友评论

          本文标题:搜索条(UISearchBar)

          本文链接:https://www.haomeiwen.com/subject/ucmbgttx.html