Я пытаюсь передать данные из ячеек в моем HomeViewController в мой CartViewController, используя закрытие (addActionHandler) в моем HomeCell.
Ранее я работал с передачей данных с использованием Tray.currentCart.cartItems.append(item)
в cellForRowAt HomeVC.
Но поскольку я изменил свой класс Tray , удалив static let currentCart = Tray()
, я не могу заставить ячейки в HomeVC передавать данные в CartVC.
Как я могу изменить код, чтобы он снова работал, чтобы передавать данные из HomeVc в CartVC после нажатия ATCBtn в домашней ячейке
Я довольно близок к своему решению, я просто не знаю, куда идти отсюда, чтобы оно работало ... любая помощь будет очень признательна
import UIKit
import Firebase
import FirebaseFirestore
class HomeViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var cartBtn: UIBarButtonItem! //segues data to CartVC
var tray: [Tray] = []
var itemSetup: [Items] = []
var selectedItem: Items?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.delegate = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? CartViewController {
vc.items = self.selectedItem
}
}
}
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: "TestCell") as? TestCell else { return UITableViewCell() }
let item = itemSetup[indexPath.row]
cell.configure(withItems: item)
cell.addActionHandler = { (option: Int) in
print("Option selected = \(option)")
// Tray.currentCart.cartItems.append(item) //old code that passed data for selected cell in HomeVC to cartVC
item.selectedOption = option
}
return cell
}
}
class CartViewController: UIViewController {
var items: Items!
var tray: [Tray] = []
@IBOutlet weak var cartTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
cartTableView.dataSource = self
cartTableView.delegate = self
}
}
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.currentCart.cartItems[indexPath.row] // code that was used to populate data in CartCells switched with new code below
let cart = tray[indexPath.row].cartItems[indexPath.section]
cell.configure(withItems: cart)
return cell
}
}
class Tray {
var cartItems = [Items]()
var cart: Items!
var brandName: String!
// static let currentCart = Tray() code that has been removed
}
1 ответ
Установите лоток класса, как показано ниже
class Tray {
var cart: Items
var brandName: String
init(cart: Items,
brandName: String) {
self.cart = cart
self.brandName = brandName
}
}
В HomeViewController в разделе addActionHandler добавьте выбранные элементы в корзину.
cell.addActionHandler = { (option: Int) in
print("Option selected = \(option)")
item.selectedOption = option
tray.append(Tray(cart: item, brandName: "<Brand Name>"))
}
Передайте лоток [] в CartViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? CartViewController {
vc.items = self.selectedItem
vc.tray = self.tray
}
}
В CartViewController передайте элементы в cartCell
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
}
Похожие вопросы
Новые вопросы
ios
iOS - мобильная операционная система, работающая на Apple iPhone, iPod touch и iPad. Используйте этот тег [ios] для вопросов, связанных с программированием на платформе iOS. Используйте связанные теги [target-c] и [swift] для проблем, характерных для этих языков программирования.