UISearchController Segue

时间:2017-04-17 13:59:23

标签: ios swift uitableview firebase uisearchcontroller

我在tableviewcontroller中有一个包含5个单元格的tableview。我希望所有单元格都能转换为searchtableviewcontroller。但是,每个细胞都是不同的受试者,当我点击一个细胞时,我希望细胞能够转变为相应的细胞。这是searchtableviewcontroller。

import UIKit
import Firebase
import FirebaseDatabase

class SearchTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {

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



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

    var databaseRef = FIRDatabase.database().reference()
    var infoRef = FIRDatabase.database().reference().child("info")
    var loggedInUser = FIRAuth.auth()?.currentUser
    let userID = FIRAuth.auth()?.currentUser?.uid
    var posts = NSMutableArray()
    var loggedUser:FIRUser?






    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true
        tableView.tableHeaderView = searchController.searchBar

        searchController.searchBar.isTranslucent = false

        searchController.searchBar.tintColor = UIColor(red:0.23, green:0.73, blue:1.00, alpha:1.0)
        searchController.searchBar.searchBarStyle = .minimal
        searchController.searchBar.placeholder = "Search Books by Title, Author & ISBN"
        searchController.searchBar.delegate = self
        searchController.searchBar.sizeToFit()
        self.searchController.hidesNavigationBarDuringPresentation = false
        self.navigationItem.title = "Search Books"


      databaseRef.child("books").observe(.childAdded, with: { (snapshot) in


        let key = snapshot.key
        let snapshot = snapshot.value as? NSDictionary
        snapshot?.setValue(key, forKey: "uid")

        if(key == self.loggedUser?.uid)
        {
            print("same as logged in user")
        }
        else
        {
        self.usersArray.append(snapshot)
             self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
        }



        }) { (error) in
            print(error.localizedDescription)
        }

    }




    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 = self.tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! TableViewCell

        let user : NSDictionary?

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

        cell.Title.text = user?["title"] as? String
        cell.Author.text = user?["Author"] as? String
        cell.ISBN.text = user?["ISBN"] as? String
        cell.Price.text = user?["Price"] as? String
        if let imageName = user?["image"] as? String {
            let imageRef = FIRStorage.storage().reference().child("images/\(imageName)")
            imageRef.data(withMaxSize: 25 * 1024 * 1024, completion: { (data, error) -> Void in
                if error == nil {

                    let image = UIImage(data: data!)
                    cell.Book.image = image

                }else {
                    print("Error downloading image:" )
                }})}

        cell.detailTextLabel?.text = user?["handle"] as? String




        return cell
    }


    func filtereContent(searchText: String)
    {
        self.filteredUsers = self.usersArray.filter{user in
           // let typeMatch = (scope == "Title") || (user?.fileType() == scope)
            let title = user!["title"] as? String
            let author = user!["Author"] as? String
            let isbn = user!["ISBN"] as? String


            return(title?.lowercased().contains(searchText.lowercased()))! || (author?.lowercased().contains(searchText.lowercased()))! || (isbn?.lowercased().contains(searchText.lowercased()))!

        }
        tableView.reloadData()

    }
}


extension SearchTableViewController{
    func updateSearchResults(for searchController: UISearchController) {

        filtereContent(searchText: self.searchController.searchBar.text!)

    }

}

这是我的tableviewcontroller,它包含要选择的单元格。

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        myIndex = indexPath.row

        if indexPath.section == 0 && indexPath.row == 0{
            performSegue(withIdentifier: "segue", sender: self)
        }
        else if indexPath.section == 0 && indexPath.row == 1{
        }
        else if indexPath.section == 0 && indexPath.row == 2{
        }
        else if indexPath.section == 0 && indexPath.row == 3{
        }
        else
        {

        }
        }

1 个答案:

答案 0 :(得分:3)

实际上你应该使用didSelectRowAtIndexPath委托的方法,并使用segue标识符为你的SearchViewController调用performSegueWithIdentifier。

self.performSegueWithIdentifier(YOUR_SEGUE_ID, sender: self)

在这种方法中,您可能想要记住所选对象的索引,因此我建议您创建一种存储所选索引的全局变量。

selectedIndex = indexPath.row

然后在prepareForSegue方法中,您可以访问destionationViewController属性。您应该明确指定正确的视图控制器

var destinationVC = segue.destinationViewController as! YOUR_VIEW_CONTROLLER_CLASS

在这些简单的操作之后,您可以自由访问SearchViewController类的所有公共变量和属性。因此,您可以将selectedIndex传递给此视图控制器。

例如:

destinationVC.selectedIndex = selectedIndex

最终在SearchViewController的viewDidLoad中,你可以诉诸这个变量,从你的数组中获取正确的项目来显示相应的数据。