【发布时间】:2019-11-14 09:13:50
【问题描述】:
我能说的最简单的方法是如何在 CartVC 中按其品牌将单元格排列成部分
因为我所做的只是在购物车中按其品牌组织单元格,这与将数据从 HomeVC 传递到购物车后我们手机中联系人的排列方式类似
代码确实成功地将数据从 HomeVC 传递到 CartVC,但单元格仍然没有按品牌名称排列
extension HomeController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as? HomeCell else { return UITableViewCell() }
let item = itemSetup[indexPath.row]
cell.configure(withItems: item)
// passes data to the Cart CartVC when ATC Btn is pressed in each cell
cell.addActionHandler = { (option: Int) in
print("Option selected = \(option)")
Tray.currentCart.cartItems.append(item)
item.selectedOption = option
}
return cell
}
}
import UIKit
class CartViewController: UIViewController {
var items: Items!
var setUp: [Items] = []
var groupedItems: [String: [Items]] = [:]
var brands: [String] = []
@IBOutlet weak var cartTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
cartTableView.dataSource = self
cartTableView.delegate = self
groupedItems = Dictionary(grouping: setUp, by: {$0.brand})
brands = groupedItems.map{$0.key}.sorted()
}
}
extension CartViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Tray.currentCart.cartItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let brand = brands[indexPath.section]
let itemToDisplay = groupedItems[brand]![indexPath.row]
// code that currently transfers data to the cells when ATC is pressed
let cart = Tray.currentCart.cartItems[indexPath.row]
cell.configure(withItems: cart)
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cartHeader = tableView.dequeueReusableCell(withIdentifier: "CartHeaderCell") as! CartHeaderCell
let headerTitle = brands[section]
return cartHeader
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
}
【问题讨论】:
-
很少有人会花一分钟以上阅读别人的问题。所以你可能想缩短你的问题。
-
你是对的,会的
-
你能在一行中写出具体的问题吗?
-
我的问题是如何在 CartVC 中按其品牌将单元格排列成部分
标签: ios swift sorting dynamic tableview