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

后端 未结 7 1452
灰色年华
灰色年华 2020-12-12 16:44

Lets consider this example:

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 
    @IBOutlet weak var tableV         


        
7条回答
  •  星月不相逢
    2020-12-12 17:19

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

提交回复
热议问题