使用Array中的值将Section添加到tableView中

时间:2016-03-03 13:29:18

标签: arrays swift uitableview struct

我有一个数组,在这个["April : 2016 : P 2 : A 28"]模式中有一些值,我想在这里添加年份2016作为一个部分,这样我就可以得到一个像这样的表格:

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

1 个答案:

答案 0 :(得分:1)

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

例如 -

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...
}
相关问题