如何解决如何快速将字典中的TableView项目分组?
您可以使用struct,这是示例:
import UIKit
class TableViewController: UITableViewController {
var names = ["vegetables": ["Tomato", "Potato", "Lettuce"], "Fruits": ["Apple", "Banana"]]
struct Objects {
var sectionName : String!
var sectionObjects : [String]!
}
var objectArray = [Objects]()
override func viewDidLoad() {
super.viewDidLoad()
for (key, value) in names {
println("\(key) -> \(value)")
objectArray.append(Objects(sectionName: key, sectionObjects: value))
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return objectArray.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objectArray[section].sectionObjects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel?.text = objectArray[indexPath.section].sectionObjects[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return objectArray[section].sectionName
}
}
解决方法
让我们考虑这个例子:
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var names = ["Vegetables": ["Tomato","Potato","Lettuce"],"Fruits": ["Apple","Banana"]]
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier:"test")
return cell
}
func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int{
return ???
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return names.count
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]!{
return ???
}
func tableView(tableView: UITableView,titleForHeaderInSection section: Int) -> String?{
return ????
}
}
假设我们需要字典的键(水果和蔬菜)是部分的数量,加上它们将是这些部分的标题。键的项目(例如苹果和香蕉)将是每个部分的行。如何在我的代码中实现呢?我知道这可能很容易,但我无法弄清楚自己的自我。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。