0

У меня есть сингл тон в который записывайся данные когда пользователь выбирает продукт после чего я передаю эти данные в корзину и отображаю их

''' 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 ответ 1

0

У вас несостыковка в логике вывода секций и продуктов внутри них - у вас 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
}
7
  • Почему то выдает out of index все равно
    – Moskwinow
    16 мар 2020 в 18:54
  • @Moskwinow посмотрите в дебаггере что там вообще в массиве получается
    – schmidt9
    16 мар 2020 в 18:59
  • В дебаггере я получаю всего навсего одно Value Блюда почему то
    – Moskwinow
    16 мар 2020 в 19:07
  • Сработало вроде как вот таким образом
    – Moskwinow
    16 мар 2020 в 19:14
  • Подскажите пожалуйста у меня теперь ошибка индекса при удалении ячейки
    – Moskwinow
    16 мар 2020 в 20:19

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.