我有一个Table视图,其数据是从Dictionary数组编译的,其中键是节标题:
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中获取的,但是如上所述,每个部分包含来自breakfastCalories数组的卡路里,午餐部分的午餐故事列表等。
答案 0 :(得分:3)
您可以使用类似的密钥构建与您的calories
属性类似的data
:
var calories: Dictionary<String,[Int]> = [
"Breakfast": [100,200,300],
"lunch": [300,400,500],
"Dinner": [600,700,800]
]
通过这种方式,您可以根据所显示的部分提取正确的卡路里,然后将它们相加以创建标签显示的总数:(在您创建页脚视图的位置添加此项,并在您设置标签的位置上方添加。文本)
let dataKeysArray = Array(data.keys)[section]
let sectionString = dataKeysArray[section]
let mealCalories = calories[sectionString]
var totalCalories: Int = 0
for calories in mealCalories {
totalCalories += calories
}
label.text = "Total Calories: \(totalCalories) "