简体   繁体   English

如何在swift中对字典中的TableView项进行分组?

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

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. 我知道这可能很容易,但我无法弄清楚自己。

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
    }
}

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 
}

From Apple Documentation : 来自Apple文档:

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

Description : A collection containing just the keys of self. Description :仅包含self键的集合。 Keys appear in the same order as they occur as the .0 member of key-value pairs in self. 键的出现顺序与self中键值对的.0成员出现的顺序相同。 Each key in the result has a unique value. 结果中的每个键都具有唯一值。

names.keys.array returns an Array of the keys. names.keys.array返回键的Array

SO: 所以:

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]
}

This will work on Any Dictionary with any amount of data(even if it is unknown to the programmer 这将适用于包含任何数据量的任何字典(即使程序员不知道

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) { $0.0 < $1.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
    }
}

All collection types must be Array 所有集合类型必须是Array

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]
}

An easier way to solve this problem is to copy your dictionary into a temporary variable. 解决此问题的更简单方法是将字典复制到临时变量中。 Use removeFirst to extract the values from the array inside the dictionary. 使用removeFirst从字典中的数组中提取值。

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
    }

Another way of solving this problem is to extract keys and values in separate arrays: 解决此问题的另一种方法是在单独的数组中提取键和值:

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
}

Similar to https://stackoverflow.com/a/31136537/11098567 answer 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() } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM