【发布时间】:2020-03-19 12:40:04
【问题描述】:
我要做的是按他们的品牌将我的单元格分成几个部分
到目前为止,我能够做的是从 HomeVC 传递所选项目的数据以填充 CartVC 的单元格
我正在尝试按品牌分隔部分,brand 数据是模型 Items 类(名称、品牌、imageUrl、价格和重量)的一部分并且 Items 类从 CloudFirestore 检索数据以填充 HomeVC 的单元格
当传递到 CartVC 时,我如何能够按其品牌将单元格分成多个部分。
到目前为止,我所做的似乎失败了,因为一旦我将一个项目从 HomeVC 传递到 CartVC,我只会得到一个标题单元格,其中包含我传递的第一个项目的 brand 名称进入 CartVC。当我将更多数据传递到 CartVC 时,所有单元格都停留在第一个项目的部分中,当我试图按他们的品牌划分我的所有 CartCells 时
extension HomeViewController: 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)
cell.addActionHandler = { (option: Int) in
print("Option selected = \(option)")
self.tray.append(Tray(cart: item))
item.selectedOption = option
}
return cell
}
}
class CartViewController: UIViewController {
var items: ProductList!
var sectionModel: [SectionModel] = []
var tray: [Tray] = []
var groupedItems: [String: [Tray]] = [:]
var brandNames: [String] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
groupedItems = Dictionary(grouping: tray, by: {$0.cart.brand})
brandNames = 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.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = tray[indexPath.row]
cell.configure(withItems: cart.cart)
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cartHeader = tableView.dequeueReusableCell(withIdentifier: "CartHeader") as! CartHeader
cartHeader.storeName.text = "Brand: \(tray[section].cart.brand)"
return cartHeader
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
}
class Tray {
var cart: ProductList!
init(cart: ProductList) {
self.cart = cart
}
}
【问题讨论】:
-
您是否尝试过在您的 CartVC 的
numberOfSections(in tableView: UITableView)方法中返回大于 1 的数字?也许像sectionModel.count这样的东西? -
我试过了,但没有用;(我将 CartVC 设置为它的基础,因为我尝试过的所有东西都没有奏效,因为我不太擅长将单元格分成表格视图中的部分
-
基本上在您的 viewDidLoad 中,您需要按品牌重新组织您的项目。您可以使用字典来做到这一点,例如:key = 品牌名称,value = 项目数组。然后您需要重新调整您的委托函数(numberOfSections、cellForRowAt 等)。你在使用 CoreData、Realm、SQLite 吗?
-
我正在使用云 Firestore 来存储我的数据 @rs7,但我刚刚在 CartVC 中更新了我的代码,我会使用这样的字典项吗?
标签: ios swift iphone uitableview uitableviewsectionheader