如何将文本字段用作表视图的“搜索栏”

时间:2019-02-08 18:44:38

标签: ios swift uitableview uiviewcontroller uitextfield

我在常规视图中嵌入了一个表格视图(如这张图片所示:Picture

我有一个搜索栏和工作代码,因此当您开始搜索某人的电子邮件时,表格视图会自动更新,并仅显示符合搜索条件的人。

有没有办法在第一个视图中将textField用作搜索栏?

(如果您查看Picture,则用户将在其中键入“ para”的标签来键入其联系人的电子邮件,我是否可以将该标签用作搜索栏,如果是,怎么样?)

换句话说,我将如何使用“ forField”作为搜索栏(forField在代码的第二位)

这是tableView的代码(当前有效):

class UsersTableViewController: UITableViewController, UISearchResultsUpdating {

    func updateSearchResults(for searchController: UISearchController) {
        //update the search results
        filterContent(searchText: self.searchController.searchBar.text!)
    }


    @IBOutlet var usersTableView: UITableView!
    let searchController = UISearchController(searchResultsController: nil)

    var usersArray = [NSDictionary?]()
    var filteredUsers = [NSDictionary?]()

    var databaseRef: DatabaseReference!


    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true

        tableView.tableHeaderView = searchController.searchBar

        databaseRef = Database.database().reference()
        let usersRef = databaseRef.child("users")
        let query = usersRef.queryOrdered(byChild: "email")
        query.observe(.childAdded, with: {(snapshot) in
            self.usersArray.append((snapshot.value as? NSDictionary?)!)

            //insert the rows
            self.usersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1, section: 0)], with: UITableView.RowAnimation.automatic)


        }) { (error) in
            print(error.localizedDescription)
        }
        print("HOLAAAAAAAAAAA")
        print(self.usersArray)

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows

        if ((searchController.isActive) && (searchController.searchBar.text != "")){
            return filteredUsers.count
        }
        return self.usersArray.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        let user: NSDictionary
        if ((searchController.isActive) && (searchController.searchBar.text != "")){
            user = filteredUsers[indexPath.row]!
        }else{
            user = self.usersArray[indexPath.row]!
        }

        cell.textLabel?.text = user["email"] as? String
        cell.detailTextLabel?.text = user["name"] as? String

        return cell
    }

    func filterContent(searchText: String){
        self.filteredUsers =  self.usersArray.filter({ user in
            let userEmail = user!["email"] as? String
            return(userEmail?.lowercased().contains(searchText.lowercased()))!
        })

        tableView.reloadData()
    }


}

对于视图控制器,它实际上只是文本字段和标签。

class PayViewController: UIViewController, STPAddCardViewControllerDelegate {       
    @IBOutlet weak var forField: UITextField!
    @IBOutlet weak var toField: UITextField!
    @IBOutlet weak var ammountLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

换句话说,我将如何使用“ forField”作为搜索栏

在最近的评论和更新之后,我在payViewController中添加了以下内容:

override func viewDidLoad() {
    super.viewDidLoad()
    //var myTable:UsersTableViewController?
    myTable = self.children[0] as! UsersTableViewController
    self.toField.addTarget(self, action: #selector(UsersTableViewController.textChanges(_:)), for: UIControl.Event.editingChanged)
}

,并在表视图控制器中更改了以下功能:

func updateSearchResults(for searchController: UISearchController) {
        //update the search results
        filterContent(searchText: searchT)
    }


    @objc func textChanges(_ textField: UITextField) {
        let text = textField.text! // your desired text here
        // Now do whatever you want.
        searchT = text
    }

1 个答案:

答案 0 :(得分:0)

您的问题是从父母那里访问孩子,因此您需要在PayViewController内声明它

var myTable:UsersTableViewController?

和viewDidLoad内部

myTable = self.children[0] as! UsersTableViewController

在此之后,textfeilds会进行动作

myTable.filterContent(searchText:forField.text!)

此外,您还可以在searchController内传输与搜索栏相关的内容,或删除该子项并在字段下方直接添加表格,然后在PayViewController内制作所有内容

  

您不必使用UITableViewController来利用表,UITableView的实例就足够了,并且可以直接作为vc中的子视图