我有一个表格视图,显示用户的姓名,公司名称和照片(PFFile)。我拥有的每个tableView行都包含所有这些信息。
我正在使用UISearchBarDelegate和IB来实现搜索功能,以按用户的名称进行过滤。它找到了正确的用户,但我无法更新公司照片。
如何过滤其他阵列?我需要从数组中获取的项目与从用户的Name数组中获取的项目相同。
编辑:我正在尝试不同的数据结构,并且接收的数组索引超出范围,更新代码如下:
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
答案 0 :(得分:2)
就像我说的那样,强烈建议您将每个用户的信息分组到一个大容器中,因此我们可以使用struct
或class
数组,然后更容易过滤。
容器示意图:
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
}
答案 1 :(得分:0)
let arr1 = [10,20,40]
let e1 = arr1.enumerate()
let arr2 = ["a","b","c"]
let f1 = e1.filter { $0.element % 20 == 0 }
let f2 = arr2.enumerate().filter { j, _ in
f1.contains { i, _ in
i == j
}
}
print(f1.map{$0.element}, f2.map{$0.element})
// [20, 40] ["b", "c"]
现在你有两个数组“已过滤”。最好的,你可以做的是重新设计你的数据模型!