我有一个 TableView ,其中包含从字典数组编译的数据,其中键是节标题:
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
下面是填充表格 View 的代码
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 数组的午餐部分等。
最佳答案
你可以构造你的 calories
类似于你的 data
属性,具有相似的键:
var calories: Dictionary<String,[Int]> = [
"Breakfast": [100,200,300],
"lunch": [300,400,500],
"Dinner": [600,700,800]
]
这样您就可以根据显示的部分提取正确的卡路里并将它们相加以创建总计以供标签显示:(将其添加到创建 footerView 的位置和设置标签的位置上方。文本)
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) "
关于ios - 为 UITableView 中的每个部分添加特定数据 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36387247/