【发布时间】:2017-08-14 18:43:50
【问题描述】:
我目前正在尝试按每行标签上的单词对我的 tableview 进行排序。每行将包含 3 项内容:颜色、动物类型和动物名称。我对如何组织表格有一个特定的顺序,但根据项目的加载方式,行的顺序可以是任何东西(问题)。
我想通过这个数组按颜色对这些表进行排序:colorArray = ["red", "blue", "yellow", "green", "orange", "purple"]。这意味着所有红色动物将排在第一位,而所有绿色动物将在中间等。第一个问题是我不知道如何通过另一个字符串数组对数组进行排序。 第二个问题是我需要另外两个数组(动物和动物名称)根据颜色数组改变它们的顺序,这样正确的动物和它们的名字就会有正确的颜色.
例子:如果颜色数组像blue, green, orange, red一样加载,而动物数组像dog, cow, cat, monkey一样加载,那么我需要将这两个数组排序到@987654324 @ 和 monkey, dog, cow, cat。所以所有的动物都有正确的颜色。 如何解决这两个问题?我在底部复制了我当前的代码:
func loadAnimals() {
let animalQuery = PFQuery(className: "Animals")
animalQuery.whereKey("userID", equalTo: PFUser.current()?.objectId! ?? String()) //getting which user
animalQuery.limit = 10
animalQuery.findObjectsInBackground { (objects, error) in
if error == nil {
self.colorArray.removeAll(keepingCapacity: false)
self.animalNameArray.removeAll(keepingCapacity: false)
self.animalTypeArray.removeAll(keepingCapacity: false)
for object in objects! {
self.colorArray.append(object.value(forKey: "colorType") as! String) // add data to arrays
self.animalNameArray.append(object.value(forKey: "animalName") as! String) // add data to arrays
self.animalTypeArray.append(object.value(forKey: "animalType") as! String) // add data to arrays
}
self.tableView.reloadData()
} else {
print(error?.localizedDescription ?? String())
}
}
}
//places colors in rows
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! AnimalCell //connects to color cell
//Adds the animal information in the cells
cell.colorType.text = colorArray[indexPath.row]
cell.animalName.text = animalNameArray[indexPath.row]
cell.animalType.text = animalTypeArray[indexPath.row]
return cell
}
【问题讨论】:
-
使用一个自定义结构或类而不是多个数组。它使生活更轻松,并附带解决您的问题。对于颜色,使用索引来获取自定义顺序。
标签: arrays swift uitableview pfquery