Как я могу проанализировать значение (Stepper) из UITableViewCell в основной контроллер View? - PullRequest
0 голосов
/ 04 марта 2019

У меня есть UITableViewCell и UIViewControllerUITableViewCell у меня есть степпер.Как я могу сделать это, когда пользователь щелкнул по степперу, чтобы отправить значение в контроллер основного представления и получить его в ячейке моего табличного представления?

Я пытался получить значение из степпера в ячейке, но он просто не 'т работа.Мой код ниже.

Первый: UITableViewCell

import UIKit
import HCSStarRatingView
import GMStepper

class FoodsSecoundTableViewCell: UITableViewCell {
    @IBOutlet weak var foodTitle: UILabel!
    @IBOutlet weak var foodPrice: UILabel!
    @IBOutlet weak var foodRating: HCSStarRatingView!
    @IBOutlet weak var foodImage: UIImageView!
    @IBOutlet weak var steperCount: GMStepper!
    var result : Double?

    override func awakeFromNib() {
        super.awakeFromNib()
        print(steperCount.value) // this line has print the value just one time
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    @IBAction func myStepper(_ sender: Any) { // its a function         
    }

}

Второй: контроллер основного вида

import UIKit

class FoodsViewController: UIViewController , UITableViewDataSource {

    var foods = [Foods]()

    @IBOutlet weak var myTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        foods = [Foods(name: "myData", price: 15, count: 0, description: "myData", time: "20 - 30 min", rating: 4, image: #imageLiteral(resourceName: "chick")),
             Foods(name: "myData", price: 30, count: 0,description: "myData", time: "20 - 30 min", rating: 5, image: #imageLiteral(resourceName: "chick")),
             Foods(name: "myData", price: 20,count: 0,description: "myData", time: "20 - 30 min", rating: 3, image: #imageLiteral(resourceName: "chick")),
             Foods(name: "myData", price: 40,count: 0, description: "myData", time: "20 - 30 min", rating: 5, image: #imageLiteral(resourceName: "chick")),
             Foods(name: "myData", price: 55, count: 0,description: "myData", time: "20 - 30 min", rating: 4, image: #imageLiteral(resourceName: "chick"))
        ]

        myTable.rowHeight = 171
        myTable.dataSource = self
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return foods.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let food = foods[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "foods")  as! FoodsSecoundTableViewCell
        cell.foodImage.image = food.image
        cell.foodPrice.text = String(food.price)
        print(cell.steperCount.value) // the result hear : its print just for one time

        cell.foodTitle.text = food.name
        cell.foodRating.value = CGFloat(food.rating)
        return cell
    }
}

Ответы [ 2 ]

0 голосов
/ 04 марта 2019

Один хороший вариант - использование шаблона делегата.Во-первых, определите протокол, которому будет соответствовать ваш VC для получения событий с измененным значением:

protocol FoodsSecoundTableViewCellDelegate: class {
  func stepper(_ stepper: GMStepper, at index: Int, didChangeValueTo newValue: Double)
}

Добавьте свойство delegate к вашему UITableViewCell и вызывайте метод делегата при каждом изменении значения на * 1006.*:

class FoodsSecoundTableViewCell: UITableViewCell {
  ...

  weak var delegate: FoodsSecoundTableViewCellDelegate?

  ...

  @IBAction func myStepper(_ sender: Any) {
    delegate?.stepper(stepper, at: stepper.tag, didChangeValueTo: stepper.value)
  }

  ...
}

Затем настройте VC на FoodsSecoundTableViewCellDelegate:

extension ViewController: FoodsSecoundTableViewCellDelegate {
  func stepper(_ stepper: GMStepper, at index: Int, didChangeValueTo newValue: Double) {
    print("Value changed in VC: \(newValue)")

    // Process that change...

    let indexPath = IndexPath(item: index, section: 0)
    guard let cell = tableView.cellForRow(at: indexPath) as? FoodsSecoundTableViewCell else {
      return
    }
    // Send the value back to the cell
  }
}

Наконец, при построении представления таблицы установите делегат степпера и тег:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let food = foods[indexPath.row]
  let cell = tableView.dequeueReusableCell(withIdentifier: "foods")  as! FoodsSecoundTableViewCell
  cell.foodImage.image = food.image
  cell.foodPrice.text = String(food.price)
  cell.foodTitle.text = food.name
  cell.foodRating.value = CGFloat(food.rating)
  cell.stepper.tag = indexPath.row
  cell.delegate = self
  return cell
}
0 голосов
/ 04 марта 2019

Вы можете взглянуть на пример кода из GMStepper .

В FoodsViewController, когда вы создаете ячейку, добавьте обратный вызов к steperCount

cell.steperCount.addTarget(self, action: #selector(FoodsViewController.stepperValueChanged), for: .valueChanged)

Добавить функцию обратного вызова:

@objc func stepperValueChanged(stepper: GMStepper) {
    print(stepper.value, terminator: "")
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...