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

后端 未结 7 1454
灰色年华
灰色年华 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:11

    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.

    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
    }
    

提交回复
热议问题