如何在IOS中使用searchBarController通过API搜索和过滤多个TableViews

时间:2018-07-29 22:41:38

标签: iphone uitableview uisearchbar

我是Xcode和Swift的新手,因此对任何幼稚的行为表示歉意。

我设法使用dropsource组合了一个应用程序,该应用程序连接了多个链接的tableViewControllers。现在,我想使用主页(第一个TableViewController)上的SearchBarController编写搜索栏,该搜索栏搜索应用程序中的所有表,并允许用户直接跳到任何表中的单元格(与搜索中的文本匹配)栏),然后点击它。

我的问题是我所有的表都使用API​​设置,但我不确定如何将数据从API连接到搜索栏。将字符串变量连接到搜索栏很简单,但是事实证明,连接API太多了。

我可以使搜索栏完美地显示在页面上,但不能将其与任何数据链接。

我特别努力的是在updateSearchResults函数中放置什么表达式来访问不同表的API /数据:

func updateSearchResults(for searchController: UISearchController) {
        //what expression should I write here to allow the search bar to     access multiple API's/tableViews    
//what expression do i follow up with here to output all the cells from all the tables that match the search term into one table   
}

这是主页上我的代码提供上下文的全部内容:

import DropKit
import UIKit

class TableViewCell114: UITableViewCell {

    @IBOutlet var label1: UILabel!

    var label1Attributes: [NSAttributedStringKey:AnyObject] = [
    .font : UIFont(name : "HelveticaNeue-Light", size : 24)!,
    .foregroundColor : UIColor(red: 0, green: 0, blue: 0, alpha: 1),
    .paragraphStyle : AttributedStringDefaults.defaultLabelParagraphStyle()
    ]

    var momentarySelectionEnabled: Bool = true {
        didSet {
            if momentarySelectionEnabled == true {
                if let indexPath = self.parent!.tableView1.indexPath(for: self) {
                    self.parent!.tableView1.deselectRow(at: indexPath, animated: true)
                }
            }
        }
    }

    var parent: HomePageViewController?
    var tableViewCell1Storage: UsersItemDataModel?
    func initialize(_ parent: HomePageViewController) {
        self.parent = parent;
        self.viewDidLoad()
    }

    func viewDidLoad() {
        self.label1.attributedText = NSAttributedString(string : "Label", attributes : self.label1Attributes)
    }
}



class HomePageViewController: UIViewController, UISearchResultsUpdating {

    // class TDSearchVC: UIViewController ,UITableViewDataSource,UITableViewDelegate , UISearchBarDelegate{

    @IBOutlet var label2: UILabel!
    @IBOutlet var tableView1: UITableView!

    //declaring the variables for the table either filtered or unfiltered
    var dataArray = [String]()
    var filteredArray = [String]()
    var shouldShowSearchResults = false
    var searchController : UISearchController!
    var resultsController = UITableViewController()

    //attributes of the label
    var label2Attributes: [NSAttributedStringKey:AnyObject] = [
    .font : UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular),
    .foregroundColor : UIColor(red: 0, green: 0, blue: 0, alpha: 1),
    .paragraphStyle : AttributedStringDefaults.defaultLabelParagraphStyle()
    ]

    //I think this is the variable that links to the API and provides the data for the table
    //maybe I could use self.tableView1Storage.filter
    var tableView1Storage: [UsersItemDataModel] = []

    //Status bar attributes
    override var preferredStatusBarStyle: UIStatusBarStyle  {
        return .default
    }

    //Show status bar
    override var prefersStatusBarHidden: Bool  {
        return false
    }


    //This is where the magic needs to happen
    //Here I think I need to access the API data to get the data for the new filtered tableView (but no idea how to do this)

    func updateSearchResults(for searchController: UISearchController) {
     //something needs to be put in here to link to the tables and then output the results   
        }

    public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        shouldShowSearchResults = true
        tableView1.reloadData()
    }


//configuring the search bar
    func configureSearchController() {
        searchController = UISearchController(searchResultsController: nil)
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search"
        searchController.searchBar.delegate = self as? UISearchBarDelegate
        searchController.searchResultsUpdater = self
        searchController.searchBar.sizeToFit()
        self.tableView1.tableHeaderView = searchController.searchBar
        self.searchController.hidesNavigationBarDuringPresentation = false;

    }




override func viewDidLoad() {
        super.viewDidLoad();
        self.navigationController?.navigationBar.barStyle = .default
        self.setNeedsStatusBarAppearanceUpdate()
        self.tableView1.separatorColor = UIColor(red: 0.047, green: 0.408, blue: 0.984, alpha: 1)
        self.tableView1.tableFooterView = UIView()

        //configuring the search bar
        configureSearchController()


        self.label2.attributedText = NSAttributedString(string : "© GOSH Apps. All Rights Reserved", attributes : self.label2Attributes)

//THIS I THINK MUST BE WHERE THE API IS ACCESSED AND RUN MAYBE THIS IS THE DATASOURCE I NEED TO FEED TO THE SEARCH BAR TO THEN FILTER??
        Manager.sharedInstance.usersGetusers(success: { (data : Data?, response : URLResponse?) -> Void in
            DispatchQueue.main.async {
                if let httpResponse = response as? HTTPURLResponse {
                    switch httpResponse.statusCode {
                        case 200:
                        if let responseJSON = data?.toJson() as? [String : Any] {
                            let responseData : Responseusers200DataTypeDataModel = Responseusers200DataTypeDataModel(dictionary: responseJSON)
                            if let unwrappedUsers = responseData.users {
                                self.tableView1Storage = unwrappedUsers;
                                self.tableView1.reloadData();
                            }
                        }
                        break
                        default: break
                    }
                }
            }
        }, failure: { (error: Error)-> Void in
        })
    }




    //This controls the back button and the attributes of the navigation bar
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.setHidesBackButton(false, animated: true)
        self.setNeedsStatusBarAppearanceUpdate()

        self.navigationController?.navigationBar.barTintColor = UIColor(red: 0.216, green: 0.439, blue: 0.353, alpha: 1)
        self.navigationController?.navigationBar.tintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
        self.navigationController?.navigationBar.titleTextAttributes = [
        .font : UIFont(name : "HelveticaNeue-Light", size : 22)!,
        .foregroundColor : UIColor(red: 1, green: 1, blue: 1, alpha: 1)
        ]
    }

    @objc func refreshControlActivated(_ refreshControl: UIRefreshControl) {

    }

}

//Why this needs to be an "extension" I don't know
//Strange that this is separated from the things above
//This appears to control the function when the cell is tapped to to another View Controller of choice

extension HomePageViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView === self.tableView1 {
            let cell = tableView.cellForRow(at: indexPath) as? TableViewCell114
            if let unwrappedCelltableViewCell1Storage = cell!.tableViewCell1Storage, let unwrappedName = unwrappedCelltableViewCell1Storage.name, unwrappedName == "Antimicrobials" {
                let destinationViewController : AntimicrobialsViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "000-000-383") as! AntimicrobialsViewController
                if let controller = self.navigationController {
                    controller.pushViewController(destinationViewController, animated: true);
                }
            }
            if let unwrappedCelltableViewCell1Storage1 = cell!.tableViewCell1Storage, let unwrappedName1 = unwrappedCelltableViewCell1Storage1.name, unwrappedName1 == "Treatment by Disease" {
                let destinationViewController1 : TreatmentByDiseaseViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "000-000-338") as! TreatmentByDiseaseViewController
                if let controller = self.navigationController {
                    controller.pushViewController(destinationViewController1, animated: true);
                }
            }
            if let unwrappedCelltableViewCell1Storage2 = cell!.tableViewCell1Storage, let unwrappedName2 = unwrappedCelltableViewCell1Storage2.name, unwrappedName2 == "Specialities" {
                let destinationViewController2 : SpecialitiesViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "000-000-087") as! SpecialitiesViewController
                if let controller = self.navigationController {
                    controller.pushViewController(destinationViewController2, animated: true);
                }
            }
            if let unwrappedCelltableViewCell1Storage3 = cell!.tableViewCell1Storage, let unwrappedName3 = unwrappedCelltableViewCell1Storage3.name, unwrappedName3 == "Hospital Map" {
                let destinationViewController3 : HospitalMapViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "000-000-671") as! HospitalMapViewController
                if let controller = self.navigationController {
                    controller.pushViewController(destinationViewController3, animated: true);
                }
            }
            if let unwrappedCelltableViewCell1Storage4 = cell!.tableViewCell1Storage, let unwrappedName4 = unwrappedCelltableViewCell1Storage4.name, unwrappedName4 == "Quick Dosing Tables" {
                let destinationViewController4 : TablesViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "000-000-102") as! TablesViewController
                if let controller = self.navigationController {
                    controller.pushViewController(destinationViewController4, animated: true);
                }
            }
            if let unwrappedCelltableViewCell1Storage5 = cell!.tableViewCell1Storage, let unwrappedName5 = unwrappedCelltableViewCell1Storage5.name, unwrappedName5 == "Infection Prevention and Control Advice Sheets" {
                let destinationViewController5 : IPCAdviceViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "000-000-308") as! IPCAdviceViewController
                if let controller = self.navigationController {
                    controller.pushViewController(destinationViewController5, animated: true);
                }
            }
            if let unwrappedCelltableViewCell1Storage6 = cell!.tableViewCell1Storage, let unwrappedName6 = unwrappedCelltableViewCell1Storage6.name, unwrappedName6 == "Prophylaxis: Surgical and Medical" {
                let destinationViewController6 : ProphylaxisViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "000-000-072") as! ProphylaxisViewController
                if let controller = self.navigationController {
                    controller.pushViewController(destinationViewController6, animated: true);
                }
            }
            if let unwrappedCelltableViewCell1Storage7 = cell!.tableViewCell1Storage, let unwrappedName7 = unwrappedCelltableViewCell1Storage7.name, unwrappedName7 == "Phone Directory" {
                let destinationViewController7 : PhoneDirectoryViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "000-000-680") as! PhoneDirectoryViewController
                if let controller = self.navigationController {
                    controller.pushViewController(destinationViewController7, animated: true);
                }
            }
            if cell!.momentarySelectionEnabled == true {
                tableView.deselectRow(at: indexPath, animated: true)
            }
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if shouldShowSearchResults {
            return filteredArray.count
        }
        if tableView === self.tableView1 {
            return self.tableView1Storage.count;
        }

        return 0;
    }
/*
     public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
     if shouldShowSearchResults {
     return filteredArray.count
     }
     else {
     return dataArray.count
     }
     }

*/

// THIS (I THINK) SETS UP THE TABLEVIEW EITHER USING self.tableView1Storage[indexPath.row] which is where the data is OR THE FILTERED TABLE VIEW

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView === self.tableView1 {
            let cell : TableViewCell114? = tableView.dequeueReusableCell(withIdentifier: "000-000-470", for: indexPath) as? TableViewCell114;
            let objectForRow = self.tableView1Storage[indexPath.row]
            cell!.tableViewCell1Storage = objectForRow
            cell!.initialize(self);
            if let unwrappedName = objectForRow.name {
                cell!.label1.attributedText = NSAttributedString(string : unwrappedName, attributes : cell!.label1Attributes);
            }

//I AM HOPING THAT THIS WILL SHOW THE FILTERED TABLE THAT MATCHES THE SEARCH TERMS
            if shouldShowSearchResults {
                cell?.textLabel?.text = filteredArray[indexPath.row]
            }
            /*else {
                cell?.textLabel?.text = dataArray[indexPath.row]

            }*/
            return cell!;
        }

        return UITableViewCell()
    }

}

0 个答案:

没有答案