【问题标题】:Show row in section with same name of row value在具有相同行值名称的部分中显示行
【发布时间】:2020-05-26 11:51:22
【问题描述】:

我有一个产品结构,取自 Firebase 数据库,如下所示:

struct Product {
    var name: String
    var type: String
    var ingredients: String
    var price: Double
}

我想用部分(产品类型)和相关行填充表格视图。 所以我创建了一个包含所有产品类型的数组:

let array = product.compactMap{$0.type}

然后我删除了重复项,并使用了最终数组作为 numberofSection 和 titleForHeaderInSections 并且它可以工作。 但现在我想在每个部分中只显示具有相同类型部分名称的产品。 我该如何解决这个问题?

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return product.count
    }

【问题讨论】:

    标签: ios arrays swift uitableview


    【解决方案1】:

    您可以按类型在字典中对产品进行分组

    let dict = Dictionary(grouping: product, by: { $0.type})
    

    然后使用您的类型数组访问它

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let type = typesArray[section]
        guard let count = dict[type]?.count else {
            return 0
        }
        return count
    }
    

    另一种选择是直接使用数组索引作为键创建字典,以便可以直接在 tableView:numberOfRowsInSection 中使用它

    Dictionary(grouping: product, by: { typesArray.firstIndex(of: prod.type)! })
    

    【讨论】:

    • 谢谢!您有在每个部分中显示相对行的解决方案吗?我正在尝试 cellForRowAt 中的一些东西,但我找不到路
    • 不确定你的意思,但你从字典中得到了每一行的行。
    • 在我的 cellForRowat 我有这个: if indexPath.section == 0 { cell.productName.text = product[indexPath.row].name
    • 我不熟悉这种类型的数组,请您解释一下如何配置 cellForRowAt?
    • 您以与上述相同的方式获取类型,但使用 indexPath.section,然后将数组作为 dict[type] 获取并使用 indexPath.row 从数组中获取行。
    【解决方案2】:

    您可以添加结构类别以便于数据操作。只需为所有产品类型创建一个类别并过滤您需要的产品。通过包含一系列产品的类别数组,您将获得所需的所有信息:产品、数量、类型等...

    struct Category {
        var type: String
        var products: [Product]
    }
    
    let allProducts = [Product]()
    let categorySet: Set<String> = allProducts.map({ $0.type }).toSet()
    
    let categorys: [Category] = categorySet.map { (type) -> T in
            return Category(type: type, products: allProducts.filter({ $0.type == type}) )
     }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return categorys.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return categorys[section].products.count
    }
    
    
    func tableView( tableView : UITableView,  titleForHeaderInSection section: Int)->String
    {
    
    return categorys[section].type
    
    }
    

    【讨论】:

    • 如果答案解释问题和解决方案,而不是仅发布代码,则答案会更有帮助(对问题的作者和该线程的未来读者)。
    【解决方案3】:

    像这样使用filter

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return product.filter { $0.type == "myType" }.count
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      • 2013-09-30
      • 2021-08-02
      相关资源
      最近更新 更多