搜索栏过滤表视图swift 4

时间:2018-05-20 07:43:39

标签: swift uitableview uisearchbar

我将尝试尽可能清楚地说明这一点。我想实现UI搜索栏来筛选JSON对象的表视图。我专门使用具有自动完成搜索功能的Yelp api。在我的课上,我向UISearchBarDelegate确认 - 从一些在线教程中,我相信我必须实现两个协议。 1是" func searchBar(textDidChange)"另一个我认为是"选择范围按钮索引确实改变了#34;。

在textdidchange函数中,我可以通过查询自动完成端点来打印出搜索列表。但我坚持如何加载这些数据(newBizName数组),以便在用户输入时搜索栏下显示结果。这是我第一次实现搜索功能,所以我有点陷入困境,任何帮助将不胜感激。谢谢

// the search bar protocol where i query the yelp endpoint - im able to get the autocomplete results as shown in the print section

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    yelpAPIClient.autocompleteBusinesses(byText: searchText, latitude: Double(Location.sharedInstance.latitude), longitude: Double(Location.sharedInstance.longitude), locale: CDYelpLocale.english_unitedStates) { (response) in

        if let response = response,
            let businesses = response.businesses,
            businesses.count > 0 {

            for business in (response.businesses)! {

                self.filteredBusinesses.append(business.name!)

            }
            self.yelpTableView.reloadData()

        }
        self.newBizName = self.filteredBusinesses
        print(self.newBizName)
        //prints after pressing P - ["Panera Bread", "Popeyes Louisiana Kitchen", "P.F. Chang\'s"]

    }


    }

func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {

}

func isFiltering() -> Bool {
    return searchController.isActive && !searchBarIsEmpty()

}

       // THE ORIGINAL TABLE VIEW THAT APPEARS UPON VIEW LOADING. 
    //I NEED TO GET THE FILTERED RESULTS INTO 
//THIS AREA AFTER THE USER CLICKS ONTO THE SEARCH BAR
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {





return (self.nameArray.count)

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "YelpCell") as? YelpCell else { return UITableViewCell() }

    cell.YelpNameLbl.text = nameArray[indexPath.row]
    cell.yelpAddressLbl.text = locationArray[indexPath.row]
    cell.yelpImg.downloadedFrom(url: yelpURLS[indexPath.row]!)
    cell.yelpDollarSignLbl.text = yelpDollarsSigns[indexPath.row]
    cell.distanceFromYou.text = String(format: "%.2f", distanceFromYou[indexPath.row]!)



    return cell

}

1 个答案:

答案 0 :(得分:0)

我认为您需要像这样重新加载表格:

DispatchQueue.main.async { 
     self.yelpTableView.reloadData()
}