使用TextField的自定义UISearchBar

时间:2019-06-07 21:50:01

标签: swift uitextfield uisearchbar

我需要使用UISearchBar进行自定义UITextField。 我尝试自己制作,但没有任何效果。请为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()
    }

}

1 个答案:

答案 0 :(得分:1)

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
}