ios 如何快速从字典中对 TableView 项目进行分组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31136084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:39:24  来源:igfitidea点击:

How can I group TableView items from a dictionary in swift?

iosswiftuitableview

提问by Rami Ammoun

Lets consider this example:

让我们考虑这个例子:

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 
    @IBOutlet weak var tableView: UITableView!

    var names = ["Vegetables": ["Tomato", "Potato", "Lettuce"], "Fruits": ["Apple", "Banana"]]

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier:"test")

    return cell
    }

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

    func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]!{

    return ???
    }

    func tableView(tableView: UITableView,
        titleForHeaderInSection section: Int) -> String?{        
    return ????
    }
}

let's assume that we need that the keys (fruits and vegetables) of the dictionary are the number of sections, plus they will be the titles of the sections. The items of the keys (eg apples and banana) will be the rows of each section. How can I implement this in my code? I know it might be easy but I couldn't figure it out my self.

让我们假设我们需要字典的键(水果和蔬菜)是部分的数量,加上它们将是部分的标题。键的项目(例如苹果和香蕉)将是每个部分的行。如何在我的代码中实现这一点?我知道这可能很容易,但我自己无法弄清楚。

回答by Dharmesh Kheni

You can use struct for that and here is example:

您可以为此使用 struct ,这是示例:

import UIKit

class TableViewController: UITableViewController {

    var names = ["Vegetables": ["Tomato", "Potato", "Lettuce"], "Fruits": ["Apple", "Banana"]]

    struct Objects {

        var sectionName : String!
        var sectionObjects : [String]!
    }

    var objectArray = [Objects]()

    override func viewDidLoad() {
        super.viewDidLoad()

        for (key, value) in names {
            println("\(key) -> \(value)")
            objectArray.append(Objects(sectionName: key, sectionObjects: value))
        }
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return objectArray.count
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objectArray[section].sectionObjects.count
    }


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

        // Configure the cell...
        cell.textLabel?.text = objectArray[indexPath.section].sectionObjects[indexPath.row]
        return cell
    }

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        return objectArray[section].sectionName
    }
}

回答by Diego

Swift 2

斯威夫特 2

you dictionary example

你的字典例子

var dic:Dictionary<String,String> = ["key":"value","key1":"value2"]

Your table

你的桌子

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

    var key   = Array(self.dic.keys)[indexPath.row]
    var value = Array(self.dic.values)[indexPath.row]
    cell.text = key + value 
}

回答by Santhosh

If you want it sorted use the global sorted function to sort the dictionary.

如果您希望对它进行排序,请使用全局排序函数对字典进行排序。

import UIKit

class TableViewController: UITableViewController {

    var names = ["Vegetables": ["Tomato", "Potato", "Lettuce"], "Fruits": ["Apple", "Banana"]]

    var namesSorted = [String, Array<String>]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Sort names
        namesSorted = sorted(names) { 
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return names.keys.array[section].count
}

func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]!{
return names.keys.array
}

func tableView(tableView: UITableView,
    titleForHeaderInSection section: Int) -> String?{        
return names.keys.array[section]
}
.0 < .0} // namesSorted = ["Fruits": ["Apple", "Banana"], "Vegetables": ["Tomato", "Potato", "Lettuce"]] } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return namesSorted.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return namesSorted[section].1.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... cell.textLabel?.text = namesSorted[indexPath.section].1[indexPath.row] return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return namesSorted[section].0 } }

回答by Raja Vikram

From Apple Documentation :

var keys: LazyForwardCollection<MapCollectionView<Dictionary<Key, Value>, Key>> { get }

Description: A collection containing just the keys of self. Keys appear in the same order as they occur as the .0 member of key-value pairs in self. Each key in the result has a unique value.

来自苹果文档:

var keys: LazyForwardCollection<MapCollectionView<Dictionary<Key, Value>, Key>> { get }

Description: 一个只包含 self 键的集合。键的出现顺序与它们作为 self 中键值对的 .0 成员出现的顺序相同。结果中的每个键都有一个唯一的值。

names.keys.arrayreturns an Arrayof the keys.

names.keys.array返回一个Array键。

SO:

所以:

var names = [["Tomato", "Potato", "Lettuce"], ["Apple", "Banana"]]
var sectionNames = ["Vegetables", "Fruits"]

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

func numberOfSectionsInTableView(tableView: UITableView) -> Int{
  return names.count
}

func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]!{

  return sectionNames
}

func tableView(tableView: UITableView,
  titleForHeaderInSection section: Int) -> String?{
    return sectionNames[section]
}

This will work on Any Dictionary with any amount of data(even if it is unknown to the programmer

这将适用于具有任何数据量的任何字典(即使程序员不知道)

回答by vadian

All collection types must be Array

所有集合类型必须是 Array

var itemList=["Grocery":["soap","flour","carrots"],"Vehicles":["oil change","gas","tire rotation"],"Household":["Cable","Tv","cellphone"]]
var itemListTmp :[String:[String]] = [:]

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text=itemListTmp[keysItem[indexPath.section]]?.removeFirst()
       //cell.textLabel?.text=itemList[indexPath.section].items[indexPath.row]
        return cell
    }

回答by pam

An easier way to solve this problem is to copy your dictionary into a temporary variable. Use removeFirstto extract the values from the array inside the dictionary.

解决这个问题的一个更简单的方法是将您的字典复制到一个临时变量中。用于removeFirst从字典内的数组中提取值。

var task=[String](itemList.keys)
var tobeDone=[[String]](itemList.values)
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return task[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text=tobeDone[indexPath.section][indexPath.row]

    return cell
}

Another way of solving this problem is to extract keys and values in separate arrays:

解决此问题的另一种方法是在单独的数组中提取键和值:

   let classInstance = Class(property1: String, property2: [CLass2.init(property1: String, property2: String)])
    let isAvailable = initialClassInstance.contains { (classInArray) -> Bool in
        if classInArray.property == classInstance.property {
            classInArray.property2.append(classInstance.property2[0])
            return true
        }
        return false
    }
    if !isAvailable {
        initialClassInstance.append(classInstance)
    }
    tableView.reloadData()
}

回答by BrooklynCoder

Similar to https://stackoverflow.com/a/31136537/11098567answer I would use classes instead of structs, so that you can manipulate or add to your values after it has been placed into the array.

类似于https://stackoverflow.com/a/31136537/11098567答案,我将使用类而不是结构,以便您可以在将值放入数组后对其进行操作或添加。

@objc func addToInitialClassInstance() {

@objc func addToInitialClassInstance() {

   let classInstance = Class(property1: String, property2: [CLass2.init(property1: String, property2: String)])
    let isAvailable = initialClassInstance.contains { (classInArray) -> Bool in
        if classInArray.property == classInstance.property {
            classInArray.property2.append(classInstance.property2[0])
            return true
        }
        return false
    }
    if !isAvailable {
        initialClassInstance.append(classInstance)
    }
    tableView.reloadData()
}
##代码##