如何过滤“updateSearchResultsForSearchController”中的字典数组来搜索带有Swift的UITableView [英] How can I filter an array of dictionaries in 'updateSearchResultsForSearchController' to search a UITableView with Swift

查看:182
本文介绍了如何过滤“updateSearchResultsForSearchController”中的字典数组来搜索带有Swift的UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经在stackoverflow上遵循了大量的指令,并观看了大量的关于如何在我的UITableView中实现搜索功能的循环。 YouTube上的视频,我觉得我知道如何实现UISearchController现在,但我正在努力如何实际过滤我的数组 updateSearchResultsForSearchController 函数。 b

我已经设法让搜索工作,如果我有一个简单的字符串值的数组,你在大多数在线实例中看到的实现搜索,但我有一个字典的数组,并不知道如何使用 .filter 来获取字典中的键/值对。

我的peopleData数组是一个数组来自JSON文件的字典,如下所示:

  {
people:[
{
ID:1,
firstname:Bob,
lastname:Smith,
age:25,
性别:男性


ID:2,
firstname:Fred,
lastname:Smith,
age:52,
gender:Male
}
]
}

$ p

我的视图控制器看起来像这样:

  //由Elliot Wainwright在26/02/2016创建。 
//版权所有©2016 Elliot Wainwright。版权所有。
$ b $导入UIKit

类SelectPersonTableViewController:UITableViewController {

var myList:NSMutableArray = []
var personData:NSMutableArray = []
var filteredPeopleData:NSMutableArray = []

var searchController:UISearchController!
var resultsController = UITableViewController()

@IBOutlet var selectPersonTable:UITableView!
$ b重写func viewDidLoad(){
super.viewDidLoad()
$ b $ guard let path = NSBundle.mainBundle()。pathForResource(PeopleData,ofType: json)else {
print(error found file)
return
}

do {
let data:NSData? = NSData(contentsOfFile:path)
如果让jsonResult:NSDictionary =
试试NSJSONSerialization.JSONObjectWithData(data !, options:NSJSONReadingOptions.MutableContainers)as? NSDictionary {
personData = jsonResult [people] as! NSMutableArray

}让错误为NSError {
print(Error:\\\
\(error))
return
}

self.resultsController.tableView.dataSource = self
self.resultsController.tableView.delegate = self

self.searchController = UISearchController(searchResultsController:self.resultsController)
self.tableView.tableHeaderView = self.searchController.searchBar
self.searchController.searchResultsUpdater = self
definePresentationContext = true

selectPersonTable.reloadData()
}

func updateSearchResultsForSearchController(searchController:UISearchController){
//过滤数组
$ b // ----------------- ----------------------------
//我不知道如何为我的数组做这个工作!
// -------------------------------------------- -

//更新结果TableView
self.resultsController.tableView.reloadData()
}
// MARK: - 表视图数据源

覆盖func numberOfSectionsInTableView(tableView:UITableView) - > Int {
return 1
}

覆盖func tableView(tableView:UITableView,numberOfRowsInSection section:Int) - > Int {
if tableView == self.tableView {
return self.peopleData.count
} else {
return self.filteredPeopleData.count
}
}

覆盖func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) - > UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cell,forIndexPath:indexPath)

if tableView == self.tableView {
person person personData {
let thisPerson = personData.objectAtIndex(indexPath.row)
cell.textLabel?.text = thisPerson [person] as?字符串
}
} else {
用于filteredPeopleData中的人{
let thisPerson = filteredPeopleData.objectAtIndex(indexPath.row)
cell.textLabel?.text = thisPerson [ 人]为? String


$ return b

$ b重写func tableView $ b myList.addObject(personData.objectAtIndex(indexPath.row))
navigationController?.popViewControllerAnimated(true)
}

// MARK: - 导航

重写func prepareForSegue(segue:UIStoryboardSegue,sender:AnyObject?){
var vc = segue.destinationViewController as! ViewController
vc.peopleList = myList
}
}

<正如你所看到的,在 ViewDidLoad 中,我得到了JSON文件的内容在'people'中。

code> personData = jsonResult [people] as! NSMutableArray 所以我最终得到了一个字典数组。

理想情况下,用户可以在UISearchBar和数组所以表格)将被过滤以显示任何包含任何包含用户所键入的部分的值的元素。所以输入ith会返回两行,因为'Smith'中出现'ith',表示数组中的两个元素。

至少,我想成为能够搜索至少一个键/值。

解决方案

试试这个:

  let results = personData.filter({如果让firstname = person [firstname] as?String,lastname = person [lastname] ?String,query = searchController.searchBar.text {
返回firstname.rangeOfString(query,options:[.CaseInsensitiveSearch,.DiacriticInsensitiveSearch])!= nil || lastname.rangeOfString(query,options:[.CaseInsensitiveSearch,。 DiacriticInsensitiveSearch])!= nil
}
return false
})
filteredPeopleData = NSMutableArray(array:results)

这将筛选具有匹配名字属性的人员。你可以为 lastname 实现类似的功能。


I've been going round in circles trying to implement search functionality in my UITableView.

I've followed loads of instructions here on stackoverflow and watched a ton of videos on YouTube and I feel like I know how to implement UISearchController now but i'm struggling how to actually filter my array in the updateSearchResultsForSearchController function.

I've managed to get search working if I have a simple array of string values as you see in most of the online examples for implementing search but I have an array of dictionaries and have no idea how to use .filter to get at the key/value pairs in the dictionary.

My peopleData array is an array of dictionaries that comes from a JSON file which looks like this:

{
  "people": [
  {
    "ID" : "1",
    "firstname" : "Bob",
    "lastname" : "Smith",
    "age" : 25,
    "gender" : "Male"
  },
  {
    "ID" : "2",
    "firstname" : "Fred",
    "lastname" : "Smith",
    "age" : "52",
    "gender" : "Male"
  }
           ]
}  


My view controller looks like this:

//  Created by Elliot Wainwright on 26/02/2016.  
//  Copyright © 2016 Elliot Wainwright. All rights reserved.

import UIKit

class SelectPersonTableViewController: UITableViewController {

    var myList:NSMutableArray = []
    var personData:NSMutableArray = []
    var filteredPeopleData:NSMutableArray = []

    var searchController : UISearchController!
    var resultsController = UITableViewController()

    @IBOutlet var selectPersonTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let path = NSBundle.mainBundle().pathForResource("PeopleData", ofType: "json") else {
            print("error finding file")
            return
        }

        do {
            let data: NSData? = NSData(contentsOfFile: path)
            if let jsonResult: NSDictionary =
                try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                    personData = jsonResult["people"] as! NSMutableArray
                }
            } catch let error as NSError {
                print("Error:\n \(error)")
                return
            }

        self.resultsController.tableView.dataSource = self
        self.resultsController.tableView.delegate = self

        self.searchController = UISearchController(searchResultsController: self.resultsController)
        self.tableView.tableHeaderView = self.searchController.searchBar
        self.searchController.searchResultsUpdater = self
        definesPresentationContext = true

        selectPersonTable.reloadData()
    }

    func updateSearchResultsForSearchController(searchController: UISearchController) {
        //Filter through the array

            //---------------------------------------------
            //I have no idea how to do this for my array!!!
            //---------------------------------------------

        //Update the results TableView
        self.resultsController.tableView.reloadData()
    }
    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.tableView {
            return self.peopleData.count
        } else {
            return self.filteredPeopleData.count
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

        if tableView == self.tableView {
            for person in personData {
                let thisPerson = personData.objectAtIndex(indexPath.row)
                cell.textLabel?.text = thisPerson["person"] as? String
            }
        } else {
            for person in filteredPeopleData {
                let thisPerson = filteredPeopleData.objectAtIndex(indexPath.row)
                cell.textLabel?.text = thisPerson["person"] as? String
            }
        }

        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        myList.addObject(personData.objectAtIndex(indexPath.row))
        navigationController?.popViewControllerAnimated(true)
    }

    // MARK: - Navigation

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        var vc = segue.destinationViewController as! ViewController
        vc.peopleList = myList
    }
}


As you can see, In ViewDidLoad I get the content of the JSON file within 'people' personData = jsonResult["people"] as! NSMutableArray so I end up with an array of dictionaries.

Ideally, users would be able to type something in the UISearchBar and the array (and so the table) would be filtered to show any elements that contain any values that include part of what the user has typed. So typing "ith" would return both rows as 'ith' appears in 'Smith' for both elements in the array.

At very least, i'd like to be able to search on at least one key/value.

解决方案

Try this:

let results = personData.filter({ person in
    if let firstname = person["firstname"] as? String, lastname = person["lastname"] as? String, query = searchController.searchBar.text {
        return firstname.rangeOfString(query, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch]) != nil || lastname.rangeOfString(query, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch]) != nil
    }
    return false
})
filteredPeopleData = NSMutableArray(array: results)

This filters people that have a matching firstname property. You could implement something similar for lastname.

这篇关于如何过滤“updateSearchResultsForSearchController”中的字典数组来搜索带有Swift的UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆