如何从弹出视图控制器获取数据到自定义表格视图单元格?

Posted

技术标签:

【中文标题】如何从弹出视图控制器获取数据到自定义表格视图单元格?【英文标题】:How to get data from popup view controller to custom table view cell? 【发布时间】:2019-03-07 20:24:08 【问题描述】:

我有 3 个视图控制器。首先是MainViewController

在此MainViewController 中,自定义表格视图单元格为FoodCell 类,其中两个属性为nameprice

我在MainViewController 中实例化这个对象,当点击到表格视图单元格时,这个对象传递到弹出窗口DetailViewController 这不是表格视图,它只有View 带有标签(foodName 和 foodPrice 标签)和AddToBasket 按钮.

最后我想将这个类对象从弹出窗口DetailViewController 传递给MyCartViewControllerMyCartViewController 是我展示foodNamesfoodPrices 对象的最后一个场景。

(例如,MainViewController 是我的食物菜单列表。DetailViewController 是我选择的食物列表。MyCartViewController 是我的市场包。)

MainViewController(食物菜单列表)

import UIKit

class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,
UICollectionViewDelegate, UICollectionViewDataSource,   UICollectionViewDelegateFlowLayout 

@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var mainTableView: UITableView!

var imageNames = [ImageNames]()
var searchFoods: [String]!
var priceFood: [Double]!
var searching = false


override func viewWillAppear(_ animated: Bool) 
    super.viewWillAppear(animated)
    self.tabBarController?.tabBar.isHidden = false


override func viewDidLoad() 
    super.viewDidLoad()

    self.navigationController?.navigationBar.isHidden = true
    let foodCell = Food(name: ["Hamburger big mac",
                               "Patates",
                               "Whopper",
                               "Steakhouse"], price: [15.0, 20.0, 25.0, 30.0])

    searchBar.delegate = self
    searchFoods = foodCell.name
    priceFood = foodCell.price

    imageNames = [
        ImageNames(name: "images"),
        ImageNames(name: "unnamed"),
        ImageNames(name: "unnamed")
    ]



func numberOfSections(in tableView: UITableView) -> Int 
    return 2


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

    return section == 0 ? 1 : searchFoods.count


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
    return indexPath.section == 0 ? 130 : 65


func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat 
    return indexPath.section == 0 ? 100 : 65


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    if indexPath.section == 0 
        let cell = tableView.dequeueReusableCell(withIdentifier: "MainFoodTableViewCell", for: indexPath) as! MainFoodTableViewCell

        cell.mainFoodCollectionView.delegate = self
        cell.mainFoodCollectionView.dataSource = self
        cell.mainFoodCollectionView.reloadData()
        cell.mainFoodCollectionView.tag = indexPath.row
        return cell

     else 

        let cell = tableView.dequeueReusableCell(withIdentifier: "CellForFood", for: indexPath) as! MainFoodTitleTableViewCell

        cell.titleLabel?.text = searchFoods[indexPath.row]
        cell.priceLabel?.text = priceFood[indexPath.row].description

        return cell
    



override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
    if segue.identifier == "cellForFoodSegue" 
        if let destinationViewController = segue.destination as? DetailViewController
        
            let indexPath = self.mainTableView.indexPathForSelectedRow!

            var foodNameArray: [String]
            var foodPriceArray: [Double]

            foodNameArray = [searchFoods[indexPath.row]]
            foodPriceArray = [priceFood[indexPath.row]]

            destinationViewController.detailFoodName = foodNameArray
            destinationViewController.detailFoodPrice = foodPriceArray

        

    


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    return  imageNames.count


//MARK:- collection view cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
    let width = UIScreen.main.bounds.width
    return CGSize(width: width, height: 130)


//MARK:- //collection view cell data
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainFoodCollectionViewCell", for: indexPath) as! MainFoodCollectionViewCell
    let img = imageNames[indexPath.row]
    cell.mainFoodImage.image = UIImage(named: img.name)
    return cell


DetailViewController(选定的食物列表)

import UIKit

class DetailViewController: UIViewController 

@IBOutlet weak var foodTitle: UILabel!
@IBOutlet weak var foodSubTitle: UILabel!
@IBOutlet weak var foodPiece: UILabel!
@IBOutlet weak var foodPrice: UILabel!
@IBOutlet weak var drinkPicker: UITextField!
@IBOutlet weak var menuPieceStepper: UIStepper!

var drinkPickerView = UIPickerView()

var selectDrinkType: [String] = []
var detailFoodName : [String] = []
var detailFoodPrice : [Double] = [0.0]



let foods = Food(name: ["Hamburger big mac",
                           "Patates",
                           "Whopper",
                           "Steakhouse"], price: [15.0, 20.0, 25.0, 30.0])


@IBAction func foodPieceStepper(_ sender: Any) 


@objc func foodPieceChangeStepper() 
    let res = menuPieceStepper.value + foods.price.first!
    foodPrice.text = "\(res)"


//TODO:- Add to basket
    @IBAction func addBasket(_ sender: Any) 

        let destinationVC = MyCartViewController()

        destinationVC.fromDetailFoodNames = foods.name
        destinationVC.fromDetailFoodPrices = foods.price
   

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
   if(segue.identifier == "addToCartSegue") 
        if let addToCartVC = segue.destination as? MyCartViewController     
            addToCartVC.fromDetailFoodNames = [foodTitle.text]
            addToCartVC.fromDetailFoodPrices = foods.price
    
   


override func viewDidLoad() 
    super.viewDidLoad()

    menuPieceStepper.value = 0.0
    menuPieceStepper.minimumValue = 0.0
    menuPieceStepper.maximumValue = 30.0
    menuPieceStepper.stepValue = foods.price.first!
    menuPieceStepper.addTarget(self, action: #selector(foodPieceChangeStepper), for: .valueChanged)

    drinkPickerView.delegate = self
    drinkPicker.inputView = drinkPickerView
    selectDrinkType = ["Ayran", "Kola", "Su", "Fanta", "Şalgam", "Sprite"]

    foodTitle.text = detailFoodName.description
    foodPrice.text = detailFoodPrice.description


    self.navigationController?.navigationItem.title = "Sipariş Detayı"
    let tapGesture = UITapGestureRecognizer(target: self, action:     #selector(self.dismissKeyboard (_:)))
    self.view.addGestureRecognizer(tapGesture)

@objc func dismissKeyboard (_ sender: UITapGestureRecognizer) 
   drinkPicker.resignFirstResponder()


override func viewWillAppear(_ animated: Bool) 
    self.navigationController?.navigationBar.isHidden = false



override func viewWillDisappear(_ animated: Bool) 
    self.navigationController?.navigationBar.isHidden = true



extension DetailViewController: UIPickerViewDelegate,    UIPickerViewDataSource 
func numberOfComponents(in pickerView: UIPickerView) -> Int 
    return 1


func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int 
    return selectDrinkType.count


func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? 
    return selectDrinkType[row]


func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 
    let selectedDrink = selectDrinkType[row]
    drinkPicker.text = selectedDrink



MyCartViewController(我的杂货袋)

import UIKit

class MyCartViewController: UIViewController, UITableViewDataSource,   UITableViewDelegate 

var fromDetailFoodNames: [String?] = []
var fromDetailFoodPrices: [Double?] = []

@IBOutlet weak var myCartTableView: UITableView!
@IBOutlet weak var totalPriceLabel: UILabel!


let foodNames = [
    "Hamburger big mac",
    "Cemal",
    "Emre",
    "Memo"
]

//TODO-: Delete my cart
@IBAction func deleteMyCart(_ sender: Any) 


//TODO: - Approve my  cart
@IBAction func approveCart(_ sender: Any) 



override func viewDidLoad() 
    super.viewDidLoad()


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

    return section == 0 ? 1 : foodNames.count


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 

     let cell = tableView.dequeueReusableCell(withIdentifier: "myCartCell", for: indexPath) as! MyCartTableViewCell

    if indexPath.section == 1 && indexPath.last! <= fromDetailFoodPrices.indices.last! 

    let name = fromDetailFoodNames[indexPath.row]?.description ?? ""
    let price = fromDetailFoodPrices[indexPath.row]
    cell.myCartFoodNameLabel?.text = name
    cell.myCartFoodPriceLabel?.text = "\(String(describing: price))₺"


    return cell    


【问题讨论】:

好的,我看到了你的流程,我有一个问题请告诉我,有没有关于详细 ViewController 的 api 用于发送数据?如果不创建字典 [String:Any] 将所有数据添加到字典 [keys : value] 中,将字典保存在用户默认的 sepete ekle 按钮上,当您在购物车视图控制器上时,获取您的字典并附加到数组 [[String:任何]] on viewdidload.... @sukhwinder-singh 不,我只是使用虚拟数据来确定我是否可以通过 3 个视图传递数据。如果我在 Detail VC 上创建字典,它将是在 DetailVC 上创建的独立数据吗?因此,这与来自 MainVC 的数据无关。 【参考方案1】:
// Create Custom delegate for him

// eg:- On PopUp View Controller 
// Create protocol
protocol PopUpVCDelegate: class 

    func refresh(text: String) 

// declare delegate var
  weak var delegate:PopUpVCDelegate?

// puting value on it 
   self.delegate?.refresh(text: self.mDateTxtFld.text!)

// On Main ViewController (Recieving Data Class)  
extension MainViewController: PopUpVCDelegate 
    func refresh(text: String) 
        self.dateLbl.text = text

    

// and don't forget to call or connect delegate when you present or push popup Vc
//like 

let resultController = self.storyboard?.instantiateViewController(withIdentifier: "PopUpVCID") as? PopUpVC       

        resultController?.delegate = self
  self.present(resultController!, animated: true, completion: nil)

// Hope Its work for you!

【讨论】:

我用协议和委托尝试了 2 次,但没有得到任何结果。您能否将您的示例与我的确切课程一起使用?我正在使用 MainViewController,这是我在那里的第一个数据。其次是来自 MainViewController 的 DetailViewController。第三个也是最重要的视图是 MyCartViewController。 但是你有 3 个 ViewController。我不知道你的 viewController 流程​​,如果可能请描述一下? 我在问题中添加了图片

以上是关于如何从弹出视图控制器获取数据到自定义表格视图单元格?的主要内容,如果未能解决你的问题,请参考以下文章

如何在swift ios中将多个图像添加到自定义表格视图单元格?

如何从自定义表格视图单元类中获取对表格视图控制器的引用

将数据从自定义表格视图单元格传递到 UIView 控制器

自定义表格视图单元格上的多个图像(Swift)

如何为自定义表格视图单元格中的按钮单击获取不同的视图控制器

RxSwift 不将数据绑定到自定义集合视图单元格