arrays - 使用数组中的值将 Section 添加到 tableView

标签 arrays swift uitableview struct

我有一个数组,其中包含此 ["April : 2016 : P 2 : A 28"] 模式中的一些值,我想添加 2016 在这里,作为一个部分,这样我就可以有一个像这样的 tableView:

2016
April : 2016   : P 92  : A 528
March : 2016   : P 42  : A 128
May : 2016   : P 12  : A 238
June : 2016   : P 23  : A 268

2017
Jan : 2016   : P 92  : A 528
April : 2016   : P 42  : A 128
Dec : 2016   : P 12  : A 238
Oct : 2016   : P 23  : A 268

我要怎么做,我累了

我创建了一个结构

    struct  datesStruct {
    var sectionYear : String!
    var sectionMonth : [String]!
}

        for set in setOfMonths {

        datesStructArray.append(datesStruct(sectionYear: "\(yearInt)", sectionMonth: newArrayofValues))
    // here `yearInt` is the year which have to be my section for records and i pulled it from the `newArrayofValues` array
        tableView.reloadData()
    }

即使现在我的表上有重复的记录,输出中也没有任何部分? 知道如何使用看起来像这样的记录中的值添加部分 ["April : 2016 : P 2 : A 28"] 任何帮助将不胜感激

更新:

现在正在获取部分,但部分重复(同一部分的重复条目)是我的代码:

    for set in setOfMonths {

     datesStructArray.append(datesStruct(sectionYear: "\(yearInt)", sectionMonth: newArrayofValues)) //  here newArrayOfValue is an array
    tableView.reloadData()
      }

我的输出:

2016
Jan : 2016   : P 92  : A 528
2016
April : 2016   : P 42  : A 128
2016
Dec : 2016   : P 12  : A 238
2017
Oct : 2017   : P 23  : A 268

但我想要的是:

2016
Jan : 2016   : P 92  : A 528
April : 2016   : P 42  : A 128
Dec : 2016   : P 12  : A 238

2017
Oct : 2017   : P 23  : A 268

最佳答案

好的,您需要将数据作为字典来维护。键是年份,值是字符串对象数组。

例如-

var dataDict = ["2017" : ["April : 2016   : P 92  : A 528", 
                          "March : 2016   : P 42  : A 128"],

                "2016" : ["Jan : 2016   : P 92  : A 528", 
                          "Feb : 2016   : P 42  : A 128"]]

现在您可以在数据源方法中返回部分数:

func numberOfSectionsInTableView(_ tableView: UITableView) -> Int{
    return dataDict.keys.count
}

您需要维护一个分类名称的排序列表,并将它们作为分类标题提供:

let sortedSectionNames = dataDict.keys.sort()

您在以下数据源方法中传递部分标题-

 func sectionIndexTitlesForTableView(_ tableView: UITableView) -> [String]?{
    return sortedSectionNames
}

现在您需要为部分的行返回配置的单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //Dequeue the cell...

    //Get the appropriate model-
    let section = indexPath.section
    let dataArray = dataDict[sortedSectionNames[section]]!
    let stringForRow = dataArray[indexPath.row]

    //Set this string into a label in your cell...
}

关于arrays - 使用数组中的值将 Section 添加到 tableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35773536/

相关文章:

ios - 观察观察者单个事件中的单个事件

ios - 将 uibuttons 从屏幕外移动到它们的位置

ios - 调整 UITableViewCell 中的 UILabel 显示错误

ios - UITableView 中的一节 Core Data 和另一节 NSMutableArray

javascript - 数组推送在使用 javascript 的 IE5 中不起作用?

javascript - 需要帮助合并 2 个位置数组和 for 循环

arrays - 返回可能组合数的递归函数

arrays - 二维数组作为 OpenCL 内核参数

ios - 完成处理程序和操作队列

swift - 无法从 Firebase 查看字典数据