Наличие нескольких кнопок в ячейке, которые передают выбранные кнопки, устанавливает данные в ячейку - PullRequest
0 голосов
/ 08 ноября 2019

У меня в ячейке три кнопки с ярлыком цены и веса, и я пытаюсь сделать это, выбрав опцию «Передать данные веса и цены в CartVC

код, который у меня есть в данный момент». в CartCell еще не публикуются данные для метки веса и цены выбранного параметра

Функция func configure, которую я установил в CartCell, работает для представления данных в ячейках для CartVC

Если в корзине отображаются имя, категория и изображение, когда нажата кнопка atcBtn для передачи данных в CartVC

Я хочу показать выбранную цену и вес в опции optionBtn (если она выбрана) вячеек CartVC, как я могу изменить код, который я установил для optionBtns в func

import UIKit
import SDWebImage
import Firebase

class Cell: UITableViewCell {

    weak var items: Items!    
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var category: UILabel!
    @IBOutlet weak var productImage: UIImageView!

    @IBOutlet weak var weightOne: UILabel!
    @IBOutlet weak var weightTwo: UILabel!
    @IBOutlet weak var weightThree: UILabel!

    @IBOutlet weak var priceOne: UILabel!
    @IBOutlet weak var priceTwo: UILabel!
    @IBOutlet weak var priceThree: UILabel!

    @IBOutlet weak var addToCart: RoundButton!

    @IBOutlet weak var optionBtn1: RoundButton!
    @IBOutlet weak var optionBtn2: RoundButton!
    @IBOutlet weak var optionBtn3: RoundButton!

    var addActionHandler: (() -> Void)?

    func configure(withItems items: Items) {
        name.text = items.name
        category.text = items.category
        image.sd_setImage(with: URL(string: items.image))
        priceOne.text = items.price1
        priceTwo.text = items.price2
        priceThree.text = items.price3
        weightOne.text = items.weight1
        weightTwo.text = items.weight2
        weightThree.text = items.weight3
        self.items = items
    }

    var lastSelectedButton = UIButton()
    @IBAction func cartTypeSelected(_ sender: RoundButton) {
        lastSelectedButton.isSelected = false; do {
            self.lastSelectedButton.backgroundColor = UIColor.blue
        lastSelectedButton = sender 
        sender.isSelected = true; do {
            self.lastSelectedButton.backgroundColor = UIColor.lightGreen
        }
    }
    @IBAction func atcBtn(_ sender: UIButton) {
        self.addActionHandler?()
    }   
}

import UIKit
import Firebase
import FirebaseFirestore

class ViewController: UITableViewController {

    @IBOutlet weak var cartButton: BarButtonItem!!
    @IBOutlet weak var tableView: UITableView!

    var itemSetup: [Items] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self

        fetchItems { (items) in
            self.itemSetup = items.sorted
            self.tableView.reloadData()
        }

    }
    func fetchItems(_ completion: @escaping ([Items]) -> Void) {
        let ref = Firestore.firestore().collection("items")
        ref.addSnapshotListener { (snapshot, error) in
            guard error == nil, let snapshot = snapshot, !snapshot.isEmpty else {
                return
            }
            completion(snapshot.documents.compactMap( {Items(dictionary: $0.data())} ))
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as? CartViewController {
            vc.items = self.itemSetup
        }
    }

    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: "Cell") as? Cell else { return UITableViewCell() }

        let item = itemSetup[indexPath.row]
        cell.configure(withItem: item)
        cell.addActionHandler = {
             Cart.currentCart.items.append(item)
        }
        return cell
    }

}

class CartViewController: UIViewController {

    var items: Items!
    @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 Cart.currentCart.cartItems.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]
        cell.configure(withItems: cart)

        return cell
    }
}

class CartCell: UITableViewCell {

    var selctedBtn: Cell?

    @IBOutlet weak var lblMealName: UILabel!
    @IBOutlet weak var imageUrl: UIImageView!
    @IBOutlet weak var lblSubTotal: UILabel!
    @IBOutlet weak var lblWeight: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    var lastSelectedButton = UIButton()
    func configure(withItems items: Items) {
        // lblWeight.text = "\(items.weight1)"
        // lblSubTotal.text = "$\(formatter.string(for: items.price1)!)"
        lblMealName.text = "\(items.category): \(items.name)"
        let formatter = NumberFormatter()
        formatter.maximumFractionDigits = 2
        formatter.numberStyle = .decimal
        imageUrl.sd_setImage(with: URL(string: items.imageUrl))

        // optionBtns I dont know how to set the code to where I can individual
        //  select a btn to pass the data to the cell
        if selctedBtn?.optionBtn1.isSelected == true {
            lblSubTotal.text = "$\(formatter.string(for: items.price1)!)"
            lblWeight.text = "\(items.weight1)"            

        } else if selctedBtn?.optionBtn2.isSelected == true {
            lblSubTotal.text = "$\(formatter.string(for: items.price2)!)"
            lblWeight.text = "\(items.weight2)"

        } else if selctedBtn?.optionBtn3.isSelected == true {
            lblSubTotal.text = "$\(formatter.string(for: items.price3)!)"
            lblWeight.text = "\(items.weight3)"

        }

       // or this

       switch lastSelectedButton {
    case selctedBtn!.optionBtn1:
        isSelected = true
        lblSubTotal.text = "$\(formatter.string(for: items.price1)!)"
        lblWeight.text = "\(items.weight1)"
    case selctedBtn!.optionBtn2:
        isSelected = true
        lblSubTotal.text = "$\(formatter.string(for: items.price2)!)"
        lblWeight.text = "\(items.weight2)"
    case selctedBtn!.optionBtn3:
        isSelected = true
        lblSubTotal.text = "$\(formatter.string(for: items.price3)!)"
        lblWeight.text = "\(items.weight3)"
    default:
        break
    }
    }  

 // still running tests to make this work just can't seem to have the selected buttons data pass to the Cart Cells
}

Обновление:

только что добавил какой-то код, который я тестировал, пока не повезло в том, как передать ярлык в корзину после нажатия кнопки выбора

1 Ответ

1 голос
/ 08 ноября 2019

Вы можете передавать значения обратно в замыканиях.

Итак, в вашем классе Cell (именование сбивает с толку - сделайте что-то вроде SelectItemCell), вы можете изменить свою переменную замыкания на:

var addActionHandler: ((Int) -> Void)?

Затем, в вашем действии addToCart, что-то вроде этого:

@IBAction func atcBtn(_ sender: UIButton) {

    // pass back the user selected values
    var i = 0
    switch lastSelectedButton {
    case optionBtn1:
        i = 1
    case optionBtn2:
        i = 2
    default:
        i = 3
    }
    self.addActionHandler?(i)

}

Это довольно неловко, и, вероятно, вы будете отслеживать фактические значения, но, например, для этогобудет работать.

Теперь в вашем VC, который содержит эту таблицу, в cellForRowAt вместо текущего:

    cell.addActionHandler = {
         Cart.currentCart.items.append(item)
    }

назначьте закрытие следующим образом:

    cell.addActionHandler = { (option: Int) in
        print("Option selected = \(option)")
        // do something based on the option that was selected
        // maybe item.selectedOption = option
        Cart.currentCart.items.append(item)
    }

Если вы хотите передать более одного значения, добавьте параметры:

var addActionHandler: ((Int, Int) -> Void)?

и в вашем действии кнопки:

self.addActionHandler?(priceVal, weightVal)

и ваше закрытие станет:

    cell.addActionHandler = { (price: Int, weight: Int) in
        // use price and weight vars
        // ...
    }

Редактировать

Если у вас еще нет свойства .selectedOption вашего класса Items, вы должны добавить одно (типа Int). Вы можете использовать это для отслеживания выбора пользователя.

Измените ваш cellForRowAt функционал следующим образом:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? Cell else { return UITableViewCell() }

    // use var to make item mutable
    var item = itemSetup[indexPath.row]

    // pass item to cell to configure labels / buttons / etc
    cell.configure(withItem: item)

    // when the "add to cart" button in the cell is tapped
    cell.addActionHandler = { (option: Int) in

    // option will be 1, 2 or 3, indicating which button the user tapped
    print("Option selected = \(option)")

        // update the .selected property of your data
        item.selectedOption = option

        Cart.currentCart.items.append(item)
    }

    return cell
}

Теперь, в вашем CartCell в вашем CartViewController, вы можетезаполните метки так:

    if items.selectedOption == 1 {
        lblSubTotal.text = "$\(formatter.string(for: items.price1)!)"
        lblWeight.text = "\(items.weight1)"            

    } else if items.selectedOption == 2 {
        lblSubTotal.text = "$\(formatter.string(for: items.price2)!)"
        lblWeight.text = "\(items.weight2)"

    } else if items.selectedOption == 3 {
        lblSubTotal.text = "$\(formatter.string(for: items.price3)!)"
        lblWeight.text = "\(items.weight3)"

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...