Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save iRiziya/b5af9b20b7930caf1cc6 to your computer and use it in GitHub Desktop.
Save iRiziya/b5af9b20b7930caf1cc6 to your computer and use it in GitHub Desktop.
Ex : Display category wise products in tableview
//Datasource
var categories:[String : [Product]] = [
"Category 1": [
Product(pTitle: "Product 1", pRate: "45"),
Product(pTitle: "Product 2", pRate: "55"),
],
"Category 2": [
Product(pTitle: "Product 3", pRate: "3"),
Product(pTitle: "Product 4", pRate: "33"),
],
]
// tableview methods
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.categories?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (categories[Array(categories.keys)[section]]?.count)!
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return Array(categories.keys)[section]
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerFrame = tableView.frame
let title = UILabel()
title.frame = (section == 0) ? CGRectMake(10, 10, 200, 20) : CGRectMake(10, 10, 200, 20)
title.font = title.font.fontWithSize(14)
title.text = self.tableView(tableView, titleForHeaderInSection: section)?.uppercaseString
title.textColor = EditFile.categoryTextColor
let headerView:UIView = UIView(frame: CGRectMake(0, 0, headerFrame.size.width, headerFrame.size.height))
headerView.addSubview(title)
return headerView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("productCell", forIndexPath: indexPath) as! ProductsTableCell
let section = Array(categories.keys)[indexPath.section]
let prod:Product = categories[section]![indexPath.row]
cell.productNameLabel.text = prod.pTitle
cell.productPriceLabel.text = prod.pTitle
return cell
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment