2016-03-03 56 views
1

我有富人在這個["April : 2016 : P 2 : A 28"]模式一些值的數組,我想補充的一年是2016這裏,作爲一個部分,這樣我可以有一個的tableView這樣的:使用值從數組添加部分插入的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() 
    } 

輸出沒有部分甚至現在我已經重複的錄音功d在我的桌子上? 任何想法我怎麼能利用它看起來記錄這樣["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

好的,您需要將數據維護爲字典。鍵是年份,值是一個字符串對象的數組。

對於示例 -

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() 

您在以下dat中傳遞節標題源方法 -

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... 
} 
+0

嘿感謝了很多!爲你的努力,我真的很感激它,我認爲這是我需要的,但你能看看我更新的問題嗎?因爲我認爲我來得太久,我即將得到我的解決方案 –

+0

嘿@shripada我試着根據你的答案,但輸出顯示只有一個部分和列?任何想法什麼是錯的,我應該告訴你我的代碼? –

+0

dataDict.keys.count正在返回1,知道爲什麼? –