ios - 在 UIViewController 中使用 UITableView 的搜索栏

标签 ios uitableview uiviewcontroller swift2 uisearchbar

我正在尝试在 json 文件的结果中进行搜索过滤。

所以我有以下代码

import UIKit
import Alamofire
import SwiftyJSON



class checkViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate{



    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var checkTable: UITableView!


     var arrRes = [[String:AnyObject]]()

    var filteredData = [[String:AnyObject]]()


    override func viewDidLoad() {
        super.viewDidLoad()
        checkTable.dataSource = self
        searchBar.delegate = self
        filteredData = arrRes



        Alamofire.request(.GET, "https://example.com/search", parameters: ["q": "", "type": "name"])
            .responseJSON { (responseData) -> Void in
                if((responseData.result.value) != nil) {
                    let swiftyJsonVar = JSON(responseData.result.value!)
                    print(swiftyJsonVar)
                    if let resData = swiftyJsonVar["data"].arrayObject {
                        self.arrRes = resData as! [[String:AnyObject]]
                    }
                    if self.arrRes.count > 0 {
                        self.checkTable.reloadData()
                    }
                }                   
        }    
    }        
     func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }        
     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {         
            return arrRes.count           
    }       
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("checkInCellView", forIndexPath: indexPath)
        var dict = arrRes[indexPath.row]
        cell.textLabel?.text = dict["name"] as? String
        return cell
    }


}

我试图在我的类中插入 UISearchResultsUpdating 但我收到一个不是成员的错误。所以我正在尝试使用 UISearchBarDelegate 但我只能在 [String] 数组中找到一种方法,而不是 [[String:AnyObject]] 在这个例子中

class ViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate {
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!

    let data = ["New York, NY", "Los Angeles, CA", "Chicago, IL", "Houston, TX",
        "Philadelphia, PA", "Phoenix, AZ", "San Diego, CA", "San Antonio, TX",
        "Dallas, TX", "Detroit, MI", "San Jose, CA", "Indianapolis, IN",
        "Jacksonville, FL", "San Francisco, CA", "Columbus, OH", "Austin, TX",
        "Memphis, TN", "Baltimore, MD", "Charlotte, ND", "Fort Worth, TX"]

    var filteredData: [String]!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        searchBar.delegate = self
        filteredData = data
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TableCell") as UITableViewCell
        cell.textLabel?.text = filteredData[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredData.count
    }

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        filteredData = searchText.isEmpty ? data : data.filter({(dataString: String) -> Bool in
            return dataString.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil
        })

    }

    // This method updates filteredData based on the text in the Search Box
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        // When there is no text, filteredData is the same as the original data
        if searchText.isEmpty {
            filteredData = data
        } else {
            // The user has entered text into the search box
            // Use the filter method to iterate over all items in the data array
            // For each item, return true if the item should be included and false if the
            // item should NOT be included
            filteredData = data.filter({(dataItem: String) -> Bool in
                // If dataItem matches the searchText, return true to include it
                if dataItem.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil {
                    return true
                } else {
                    return false
                }
            })
        }
        tableView.reloadData()
    }
}

有什么方法可以使 [[String:AnyObject]] 也适用吗???

因为如果我尝试这样做,我会得到一个错误

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    filteredData = searchText.isEmpty ? arrRes : arrRes.filter({(dataString: [String:AnyObject]) -> Bool in
        return dataString.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil
    })

}

“[String : AnyObject]”类型的值没有成员“rangeOfString”

知道如何处理这个吗?

最佳答案

希望您能从下面的代码中得到启发。

override func viewDidLoad() 
{
    super.viewDidLoad()

    var MyStringArray: [String] = ["ABC","XYZ","SomeData"]

    let strDemo : String = "SomeData"

    for indexNo in 0..<MyStringArray.count 
    {

        if MyStringArray[indexNo].rangeOfString(strDemo) != nil
        {
            print("found")
        }
        else
        {
            print("Not found")
        }
    }

}

关于ios - 在 UIViewController 中使用 UITableView 的搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36859909/

相关文章:

iphone - 将 NSPredicate 与嵌套数组 ios 一起使用

ios - 更改 View 后 UITabBar iAd 横幅未正确加载

ios - 仅从动态 TableView 的一个单元格推送或继续新 View 的正确方法是什么

ios - iOS Swift numberOfSectionsInTableView VS numberOfRowsInSection

ios - 如何将文本字段用作 TableView 的 "search bar"

ios - 滚动 UITableView 时 UIImageViews 变黑

ios - Xcode 9 iOS 模拟器在安装 Xcode 10 beta 后变成黑屏

uitableview - 表格单元格快速显示 NSMutableArray 的第一个索引数据

objective-c - 克隆或复制 UIViewController 或 UIView

ios - 在 CNContactViewController 中预加载/显示数据(swift)