UITableView проблемы с созданием Sections
У меня есть сингл тон в который записывайся данные когда пользователь выбирает продукт после чего я передаю эти данные в корзину и отображаю их
''' import UIKit
final class BasketModel {
static let shared = BasketModel()
var records: [Products] = []
private init() {}
func addProducts(_ product: Products) {
self.records.append(product)
}
func clearProducts() {
self.records = []
}
}
struct Products {
let img: UIImage
let name: String
let price: Int
let type: String
} '''
У меня есть три продукта ( Блюда, Топпинги, Напитки) я хочу создать 3 секции с такими данными Блюда, Топпинги, Напитки вот мой код таблицы
''' import UIKit
class BasketVC: UIViewController {
@IBOutlet weak var fullBasketview: UIView!
@IBOutlet weak var bottomBasketView: UIView!
@IBOutlet weak var choiceBtn: UIButton!
@IBOutlet weak var basketTableView: UITableView!
@IBOutlet weak var totalPriceLabel: UILabel!
@IBOutlet weak var orderButton: UIButton!
var presenter = false
var totalPrice = 0
var sections: [String] = ["Блюда","Топпинги","Наппитки"]
var product = [BasketModel.shared.records]
override func viewDidLoad() {
super.viewDidLoad()
choiceBtn.layer.cornerRadius = 20
choiceBtn.layer.masksToBounds = true
basketTableView.delegate = self
basketTableView.dataSource = self
orderButton.layer.cornerRadius = 20
orderButton.layer.masksToBounds = true
if !BasketModel.shared.records.isEmpty {
fullBasketview.isHidden = false
for item in BasketModel.shared.records {
totalPrice += item.price
totalPriceLabel.text = "\(totalPrice) Руб."
}
} else {
fullBasketview.isHidden = true
}
}
@IBAction func unwindBasketVC(for unwindSegue: UIStoryboardSegue) {}
}
extension BasketVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return product[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BasketCell", for: indexPath) as! BasketCell
cell.basketImg.image = product[indexPath.section][indexPath.row].img
cell.basketName.text = product[indexPath.section][indexPath.row].name
cell.basketPrice.text = "\(product[indexPath.section][indexPath.row].price) Руб."
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
BasketModel.shared.records.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
totalPrice = 0
for item in BasketModel.shared.records {
totalPrice += item.price
totalPriceLabel.text = "\(totalPrice) Руб."
}
}
if BasketModel.shared.records.isEmpty {
fullBasketview.isHidden = true
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
'''
После того того как я перейду в корзину ошибка появляется тут ''' func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return product[section].count -> Fatal error: Index out of range
}
'''
Помогите пожалуйста
Ответы (1 шт):
У вас несостыковка в логике вывода секций и продуктов внутри них - у вас 3 секции, но при этом вот здесь var product = [BasketModel.shared.records] product будет содержать лишь один вложенный массив со всеми продуктами без разделения на секции
Если у вас продукты идут единым массивом (скажем их 10 и они для разных секций), то вам надо их сначала рассортировать по какому-то признаку например type (что отнести к блюдам, топингам и тд)
struct Product {
let img: UIImage
let name: String
let price: Int
let type: String
}
var productsList = BasketModel.shared.records
var sections: [String] = ["Блюда","Топпинги","Напитки"]
var sectionedProducts: [[Product]] = []
// пусть type будет содержать имя секции
sections.forEach { section in
let itemsInSection = productsList.filter { $0.type == section }
sectionedProducts.append(itemsInSection)
}
// ...
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionedProducts[section].count
}