【发布时间】:2020-03-16 10:02:21
【问题描述】:
我有来自另一个 ViewController 的代码,它通过闭包传递数据以填充 CartVC 中的单元格,该单元格传递数据以成功填充单元格
我现在要做的是让我的 CartVC 按其品牌将单元格排列成部分。但是传递到 Tableview 的所有数据最终都会将单元格打乱成随机部分
我一直在尝试按brand在我的tableview行中按字母顺序按部分对数据进行排序。我设法创建了部分和索引,但不知道如何让 brands 进行排序;品牌的每个部分都从 A-Z 排序,并在 CartHeaderCell 中使用品牌的完整短语。
Items 的模型类有对象:名称、品牌、价格、重量、imageUrl 和类别。 tableView 通过cell.configure(withItems: cart) 显示名称、图像、重量、价格和类别,以填充 CartCells 和 CartHeaderCells 中的品牌
import UIKit
class CartViewController: UIViewController {
var items: Items!
var setUp: [Tray] = []
var groupedItems: [String: [Tray]] = [:]
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 Tray.currentCart.cartItems.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Tray.currentCart.cartItems[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let itemToDisplay = groupedItems[brands[indexPath.section]]![indexPath.row]
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
cartHeader.storeName.text = "Brand: \(Tray.currentCart.cartItems[section].brand)"
return cartHeader
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
}
class Tray {
static let currentCart = Tray()
var cartItems = [Items]()
var cart: Items!
}
我已经尝试了 20 多种不同的方法来完成这项工作,但没有任何帮助。任何建议将不胜感激。提前致谢!
【问题讨论】:
-
一些澄清会有所帮助。
Tray的用途是什么,为什么它同时有一个Items和一个Items数组?setup数组是所有购买的“篮子”吗?添加实际的Items类定义也可能会有所帮助。 -
在您的表格读取数据以填充单元格之前,该数据应该完全符合您想要的形状、大小和顺序。创建一种方法来清理您的数据,将它们放置在单独的数组中或在加载表格之前,如果有必要满足您的部分需求,字典(例如)。
-
我删除了我的答案,因为您的代码令人困惑。您的班级
Tray没有brand属性,因此分组行中的{$0.brand}无论如何都无法工作。
标签: ios arrays swift uitableview sorting