显示TableView Section Headers和Rows ios swift

时间:2017-11-17 05:57:43

标签: ios uitableview swift3

我有一个包含对象的数组,我想在标题中显示组名,但在数组中有些组具有相同的名称,现在我想显示同一组的单个标题并创建行。
[
       {
         "primary_dark_color": "#0d6d9f",
         "Groups": "A",
         "primary_color": "#03a9f4"
       },
       {
         "primary_dark_color": "#0d6d9f",
         "Groups": "B",
         "primary_color": "#03a9f4"
        },
        {
         "primary_dark_color": "#0d6d9f",
         "Groups": "A",
         "primary_color": "#03a9f4"
        },
        {
         "primary_dark_color": "#0d6d9f",
         "Groups": "B",
         "primary_color": "#03a9f4"
       }]

1 个答案:

答案 0 :(得分:0)

要解决您的问题,您需要使用谓词。使用谓词,您可以制作包含相同组的字典的组(数组)

尝试下面的代码。

let array = [
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "A",
        "primary_color": "#03a9f4"
        ],
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "B",
        "primary_color": "#03a9f4"
        ],
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "A",
        "primary_color": "#03a9f4"
        ],
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "B",
        "primary_color": "#03a9f4"
        ]]

    var arrGroups = [String]()
    for dict in array {

        if !arrGroups.contains(dict["Groups"]!) {

            arrGroups.append(dict["Groups"]!)
        }
    }
    var arrTmp = [Array<Dictionary<String, String>>]()
    for i in 0..<arrGroups.count {

        var tmp:Array = array
        tmp = tmp.filter { ($0["Groups"]!).range(of: arrGroups[i], options: [.diacriticInsensitive, .caseInsensitive]) != nil }
        arrTmp.append(tmp)
    }
    print(arrTmp)

arrTmp中的每个数组都包含包含相同组的字典

所以你的numberOfSections = arrTmp.count

numberOfRowsInSection = arrTmp[section].count

arrTmp将有

[[["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "A"], ["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "A"]], [["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "B"], ["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "B"]]]