我已经做到了:
var data = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry",
"Clementine", "Coconut", "Cranberry", "Fig", "Grape", "Grapefruit",
"Kiwi fruit", "Lemon", "Lime", "Lychee", "Mandarine", "Mango",
"Melon", "Nectarine", "Olive", "Orange", "Papaya", "Peach",
"Pear", "Pineapple", "Raspberry", "Strawberry"]
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 12
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellLabel", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel?.text = data[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return months[section]
}
现在我如何选择数据数组中的哪些变量进入哪个“月”部分?有没有我应该使用的方法,我不知道? (这是一个扩展UITableView的类)
答案 0 :(得分:2)
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
和tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
有section和indexPath参数,indexPath有section
变量。所以基本上你应该在这些函数中做一些switch语句来根据月份返回所需的数据。每个月拥有一组数据可能是个更好的主意。或者是多维数组,甚至是一些自定义数据类型。
无论如何,代码可能是这样的:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return dataJanuary.count
}
else if section == 1 {
return dataFebruary.count
}
// ...
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellLabel", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
if indexPath.section == 0 {
cell.textLabel?.text = dataJanuary[indexPath.row]
}
else if indexPath.section == 1 {
cell.textLabel?.text = dataFebruary[indexPath.row]
}
// ...
return cell
}