使用 TextField 的自定义 UISearchBar



我需要使用 UITextField 制作自定义UISearchBar。我尝试自己制作,但没有任何效果。请为 UITextField 编写一个代码,它将像 UISearchBar 一样工作这是我使用 UISearchBar 的代码,但我需要更改为 UITextField

class FoodViewController: UIViewController {
    override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }
    let tableView = UITableView()
    var foods = [FoodModel]()
    var searchedFoods = [FoodModel]()
    var searching = false

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchFoods()
        self.modalPresentationCapturesStatusBarAppearance = true
        self.view.backgroundColor = UIColor.white
        let controller = UIViewController()

        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")

        self.view.addSubview(self.tableView)


        tableView.delegate = self
        tableView.dataSource = self

        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 5, width: 350, height: 40))
        searchBar.searchBarStyle = .minimal
        searchBar.barStyle = .black
        searchBar.delegate = self
        self.view.addSubview(searchBar)

    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.updateLayout(with: self.view.frame.size)
    }
    func updateLayout(with size: CGSize) {
        self.tableView.frame = CGRect.init(x: 0, y: 45, width: size.width, height: 400)
    }
    func fetchFoods() {
        Database.database().reference().child("food").observe(.childAdded) { (snapshot) in
            if let dict = snapshot.value as? [String: AnyObject] {
                let newTitle = dict["title"] as! String
                let exCell = FoodModel(title: newTitle)
                self.foods.append(exCell)
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}


extension FoodViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        if searching {
            let food = searchedFoods[indexPath.item]
            cell.textLabel?.text = food.title
        } else {
            let food = foods[indexPath.item]
            cell.textLabel?.text = food.title
        }
        return cell

    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searching {
            return searchedFoods.count
        } else {
            return foods.count
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            var titleOfFood = String()
            if searching == true {
               titleOfFood = searchedFoods[indexPath.row].title
                 print(titleOfFood)
            } else {
                titleOfFood = foods[indexPath.row].title
                 print(titleOfFood)
            }
        let alertController = UIAlertController(title: "Hello", message: "Message", preferredStyle: .alert)
        let cancel = UIAlertAction(title: "Cancel", style: .default)
        let save = UIAlertAction(title: "Save", style: .cancel) { (action) in
             self.dismiss(animated: true, completion: nil)
        }
        alertController.addTextField { (textField) in
            textField.keyboardType = .numberPad
            textField.borderStyle = .roundedRect
            textField.layer.borderColor = UIColor.clear.cgColor
            textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 50))
            textField.font = UIFont(name: "Roboto-Medium", size: 30)
           // textField.cornerRadius = 8
        }
        alertController.addAction(save)
        alertController.addAction(cancel)
        self.present(alertController, animated: true)
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    }
}
extension FoodViewController: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == self.tableView {
            SPStorkController.scrollViewDidScroll(scrollView)
        }
    }
}
extension FoodViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchedFoods = foods.filter({ $0.title.lowercased().prefix(searchText.count) == searchText.lowercased() })
        searching = true
        tableView.isHidden = false
        tableView.reloadData()
        let transitionDelegate = SPStorkTransitioningDelegate()
        transitionDelegate.customHeight = 620
        transitionDelegate.showIndicator = false
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searching = false
        searchBar.text = ""
        tableView.reloadData()
    }
}

基本上(如果我理解正确的话(在将UITextField添加到视图中后,您所需要的只是在UITextField的值发生变化时触发一些方法。

像这样:

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

然后:

func textFieldDidChange(_ textField: UITextField) {
    let searchText = textField.text!
    searchedFoods = foods.filter({ $0.title.lowercased().prefix(searchText.count) == searchText.lowercased() })
    searching = true
    tableView.isHidden = false
    tableView.reloadData()
    let transitionDelegate = SPStorkTransitioningDelegate()
    transitionDelegate.customHeight = 620
    transitionDelegate.showIndicator = false
}

最新更新