gpt4 book ai didi

arrays - 用于 UISearchBar 的过滤数组

转载 作者:搜寻专家 更新时间:2023-11-01 07:27:47 24 4
gpt4 key购买 nike

我有一个显示用户姓名、公司名称和照片 (PFFile) 的表格 View 。我拥有的每个 tableView 行都包含所有这些信息。

我正在使用 UISearchBarDelegate 和 IB 来实现一个搜索功能,以按用户名进行过滤。它找到了正确的用户,但我还无法更新公司照片。

如何过滤其他数组?我需要从数组中获取的项与从用户的名称数组中获取的项位于相同的索引处。

编辑:我正在尝试不同的数据结构并收到超出范围的数组索引,更新代码如下:

var filterArray = [User]()  //<-- globally declared
var userArray = [User]() //< Global


class User {

var name: String?
var company: String?

init (name: String?, company: String?) {

self.name = name
self.company = company
}
}
//In a class which populates the search arrays
for object in unwrappedSucceeded {

let username = object.valueForKey("username") as! String
let companyName = object.valueForKey("companyName") as! String
let user = User(name: username, company: companyName)

userArray.append(user)
}

//tableViewController

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

filterArray.removeAll(keepCapacity: false)

if searchText.characters.count != 0 {
isSearch = true

self.search(searchText)

} else {
isSearch = false
}
}


func search(text: String) -> Void {

filterArray = userArray.filter({$0.name == text})

}
//In cellForRowAtIndexPath
cell.usernameCell.text = filterArray[indexPath.row].name //ARRAY INDEX OUT OF RANGE

最佳答案

就像我说的,你强烈建议将每个用户的信息分组到一个大容器中,因此我们可以使用 structclass 的数组,这样就更容易过滤。

容器示意图:

struct Container
{
var username:String?
var companyName:String?
var photo:UIImage?
}

您的主数组将是:var arrayofData = [Container]()

现在,当您在查询函数中通过解析查询对象时

// after you called the findObjectsWithBackgroundBlock()
// let's assume you check for error and if the [PFObject] is empty or not

for one in objectsFromParse
{
let photoToget = one["Photo"] as! PFFile
// next step should be to get the image data right :)
{
// let's assume that is the block when get the image data right:)
// check your data and assign it to some UIImage
// then
let userRepresentation = Container() //<-- we are creating a single object representation for each user

let username = one["username"] as! String //<--data we got from Parse
let companyName = one["companyName"] as! String
let userImage = //the UIImage which contains the data

userRepresentation.username = username
userRepresentation.companyName = companyName
userRepresentation.photo = userImage

// then we append
arrayOfData.append(userRepresentation)
}
}

现在我们已将所有数据放入我们的数组中,所以让我们按用户名过滤,同时我希望您配置 tableView,这样当您有来自过滤器或常规数组的数据时。

  var filterArray = [Container]()  //<-- globally declared

func search(text: String) -> Void
{
filterArray = arrayOfData.filter(){ (Container) -> Bool in
let range = Container.name!.rangeOfString(text, options:NSStringCompareOptions.CaseInsensitiveSearch) return range != nil }
// then you are good to go
}

关于arrays - 用于 UISearchBar 的过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34832019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com