Swift 使用TextField的自定义UISearchBar

Swift 使用TextField的自定义UISearchBar,swift,uitextfield,uisearchbar,Swift,Uitextfield,Uisearchbar,我需要使用UITextField定制UISearchBar。 我试着自己做,但没有效果。请为UITextField编写一个代码,它将像UISearchBar一样工作 这是我使用UISearchBar的代码,但我需要更改为UITextField class FoodViewController: UIViewController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent

我需要使用
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
}

非常感谢。我有个问题。您知道如何在SPStorkController中更改高度吗。例如,我有FirstVC,单击按钮并打开SPStorkController。并使高度
transitionlegate.customHeight=620
。我知道怎么做。但是如果我需要改变里面的高度该怎么办呢。在我的SPStorkController(FoodVC)中,我有一个按钮/文本字段。当我点击它时,我想改变高度。怎么做?你知道吗?