2
我有與來自字典陣列編譯的數據的表圖,其中鍵是節頭:添加特定數據用於UITableView的每個部分 - SWIFT
var data: Dictionary<String,[String]> = [
"Breakfast": ["Oatmeal","Orange Juice"],
"lunch": ["Steak","Mashed Potatoes","Mixed Veg"],
"Dinner": ["Chicken","Rice"],
"Snack": ["Nuts","Apple"]
]
var breakfastCalories = [100,200,300]
var lunchCalories = [300,400,500]
var DinnerCalories = [600,700,800]
var breakfast = 0
下面是用於填充表視圖
代碼override func viewDidLoad() {
super.viewDidLoad()
for value in breakfastCalories as NSArray as! [Int]{
breakfast = breakfast + value
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
let sectionString = Array(data.keys)[section]
return data[sectionString]!.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionString = Array(data.keys)[section]
return sectionString
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
let sectionString = Array(data.keys)[indexPath.section]
cell.caloriesLabel.tag = indexPath.row
cell.caloriesLabel.text = String(breakfastCalories[indexPath.row])
cell.foodLabel.tag = indexPath.row
cell.foodLabel.text = data[sectionString]![indexPath.row]
return cell
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
// self.myTableView.tableFooterView = footerView;
let label = UILabel(frame: CGRectMake(footerView.frame.origin.x - 15, footerView.frame.origin.y, footerView.frame.size.width, 20))
label.textAlignment = NSTextAlignment.Right
label.text = "Total Calories: \(breakfast) "
footerView.addSubview(label)
return footerView
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 20.0
}
我的問題是,我怎麼能爲每個部分添加卡路里數組?所以吃早餐時,它將包含從breakfastCalories陣列,午餐節的lunchCalories陣列的卡路里等
我可能這得太多,但我不能讓我的頭圍繞這個問題
感謝
在值從breakfastCalories抓起然而,由於提到的每個部分的權利包含來自breakfastCalories陣列,午餐節的lunchCalories陣列的卡路里等
這個解決方案有一定道理,但我對mealCalories得到一個出乎意料的發現,零誤差 – user3423164
沒關係,只是一個愚蠢的錯誤。我沒有爲我的零食添加卡路里,因此它被設置爲零。感謝您的迅速解決方案 – user3423164